"use strict";
/**
 * File Writer
 * Handles writing generated files to disk with retry logic
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileWriter = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const retry_manager_1 = require("../utils/retry-manager");
class FileWriter {
    /**
     * Write generated files to disk
     */
    async write(files, options = {}) {
        const result = {
            written: [],
            skipped: [],
            errors: [],
        };
        const total = files.length;
        let current = 0;
        for (const file of files) {
            try {
                // Report progress before writing
                if (options.onProgress) {
                    options.onProgress({
                        stage: 'Writing Files',
                        current,
                        total,
                        file: file.path,
                        message: `Writing ${path.basename(file.path)}`,
                    });
                }
                await this.writeFile(file, options, result);
                current++;
                // Report progress after writing
                if (options.onProgress) {
                    options.onProgress({
                        stage: 'Writing Files',
                        current,
                        total,
                        file: file.path,
                        message: `Wrote ${path.basename(file.path)}`,
                    });
                }
            }
            catch (error) {
                result.errors.push({
                    path: file.path,
                    error: error instanceof Error ? error.message : String(error),
                });
                current++;
            }
        }
        return result;
    }
    /**
     * Write a single file with retry logic
     */
    async writeFile(file, options, result) {
        const absolutePath = path.resolve(file.path);
        // Check if file exists
        const exists = await retry_manager_1.RetryHelpers.retryFileOperation(async () => fs.existsSync(absolutePath), 'check file existence');
        // Skip if file exists and overwrite is false
        if (exists && file.overwrite === false) {
            if (options.verbose) {
                console.log(`Skipping ${file.path} (file exists, overwrite=false)`);
            }
            result.skipped.push(file.path);
            return;
        }
        // Handle preserve mode (future enhancement)
        if (exists && file.preserve) {
            // TODO: Implement smart merging
            // For now, just skip
            if (options.verbose) {
                console.log(`Skipping ${file.path} (preserve mode)`);
            }
            result.skipped.push(file.path);
            return;
        }
        // Dry run mode
        if (options.dryRun) {
            if (options.verbose) {
                console.log(`Would write ${file.path} (dry run)`);
            }
            result.written.push(file.path);
            return;
        }
        // Ensure directory exists with retry
        const dir = path.dirname(absolutePath);
        await retry_manager_1.RetryHelpers.retryFileOperation(async () => {
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        }, `create directory ${dir}`);
        // Write file with retry
        await retry_manager_1.RetryHelpers.retryFileOperation(async () => {
            fs.writeFileSync(absolutePath, file.content, 'utf-8');
        }, `write file ${path.basename(file.path)}`);
        if (options.verbose) {
            console.log(`Wrote ${file.path}`);
        }
        result.written.push(file.path);
    }
    /**
     * Delete a file with retry logic
     */
    async delete(filePath, options = {}) {
        const absolutePath = path.resolve(filePath);
        const exists = await retry_manager_1.RetryHelpers.retryFileOperation(async () => fs.existsSync(absolutePath), 'check file existence');
        if (!exists) {
            return false;
        }
        if (options.dryRun) {
            if (options.verbose) {
                console.log(`Would delete ${filePath} (dry run)`);
            }
            return true;
        }
        await retry_manager_1.RetryHelpers.retryFileOperation(async () => {
            fs.unlinkSync(absolutePath);
        }, `delete file ${path.basename(filePath)}`);
        if (options.verbose) {
            console.log(`Deleted ${filePath}`);
        }
        return true;
    }
    /**
     * Check if a file exists with retry logic
     */
    async exists(filePath) {
        return retry_manager_1.RetryHelpers.retryFileOperation(async () => fs.existsSync(path.resolve(filePath)), 'check file existence');
    }
    /**
     * Read a file with retry logic
     */
    async read(filePath) {
        return retry_manager_1.RetryHelpers.retryFileOperation(async () => fs.readFileSync(path.resolve(filePath), 'utf-8'), `read file ${path.basename(filePath)}`);
    }
}
exports.FileWriter = FileWriter;
//# sourceMappingURL=file-writer.js.map