"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditedFilesSchema = exports.FileOperationSchema = void 0;
exports.applyFileOps = applyFileOps;
const zod_1 = require("zod");
const path_1 = __importDefault(require("path"));
const promises_1 = __importDefault(require("fs/promises"));
const chalk_1 = __importDefault(require("chalk"));
const utils_1 = require("../utils");
/**
 * Represents a file operation, including modifications, deletes, and moves.
 */
exports.FileOperationSchema = zod_1.z.object({
    /**
     * Absolute path to the file.
     */
    path: zod_1.z.string(),
    /**
     * FULL CONTENT of the file after modification. Provides the FULL AND FINAL content of
     * the file after modification WITHOUT OMITTING OR TRUNCATING ANY PART OF THE FILE.
     *
     * Mutually exclusive with 'delete' and 'move_to'.
     */
    updated_full_content: zod_1.z.string().nullable().optional(),
    /**
     * Set to true if the file is to be deleted.
     *
     * Mutually exclusive with 'updated_full_content' and 'move_to'.
     */
    delete: zod_1.z.boolean().nullable().optional(),
    /**
     * New path of the file if it is to be moved.
     *
     * Mutually exclusive with 'updated_full_content' and 'delete'.
     */
    move_to: zod_1.z.string().nullable().optional(),
});
/**
 * Container for one or more FileOperation objects.
 */
exports.EditedFilesSchema = zod_1.z.object({
    /**
     * A list of file operations that are applied in order.
     */
    ops: zod_1.z.array(exports.FileOperationSchema),
});
function applyFileOps(ops) {
    return __awaiter(this, void 0, void 0, function* () {
        utils_1.logger.info("[FILE_OPS] appying file operations.");
        for (const op of ops) {
            if (op.delete) {
                utils_1.logger.info("[FILE_OPS] Deleting file: " + op.path);
                try {
                    yield promises_1.default.unlink(op.path);
                }
                catch (err) {
                    utils_1.logger.error(chalk_1.default.red("[FILE_OPS] Failure in applying fileOp delete: ") + op.path);
                }
            }
            else if (op.move_to) {
                utils_1.logger.info("[FILE_OPS] Moving file: " + op.path + " -> " + op.move_to);
                const newContent = op.updated_full_content || "";
                try {
                    yield promises_1.default.mkdir(path_1.default.dirname(op.move_to), { recursive: true });
                    yield promises_1.default.writeFile(op.move_to, newContent, "utf-8");
                }
                catch (err) {
                    utils_1.logger.error(chalk_1.default.red("[FILE_OPS] Failure in applying fileOp move_to: "));
                }
                try {
                    utils_1.logger.info("[FILE_OPS] Finishing move by deleting: " + op.path);
                    yield promises_1.default.unlink(op.path);
                }
                catch (err) {
                    utils_1.logger.error(chalk_1.default.red("[FILE_OPS] Failure in applying fileOp delete for move: ") + op.path);
                }
            }
            else {
                utils_1.logger.info("[FILE_OPS] Updating file: " + op.path);
                const newContent = op.updated_full_content || "";
                try {
                    yield promises_1.default.mkdir(path_1.default.dirname(op.path), { recursive: true });
                    yield promises_1.default.writeFile(op.path, newContent, "utf-8");
                }
                catch (err) {
                    utils_1.logger.error(chalk_1.default.red("[FILE_OPS] Failure in applying fileOp update") + op.path);
                }
            }
        }
    });
}
