"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeFileEditOperation = executeFileEditOperation;
const fileCommon_1 = require("./fileCommon");
const Runtime_1 = require("../../runtime/Runtime");
const helpers_1 = require("../../utils/runtime/helpers");
/**
 * Shared execution pipeline for file edit tools.
 * Handles validation, file IO, diff generation, and common error handling.
 */
async function executeFileEditOperation({ config, filePath, operation, abortSignal, }) {
    try {
        // Validate no redundant path prefix (must come first to catch absolute paths)
        const redundantPrefixValidation = (0, fileCommon_1.validateNoRedundantPrefix)(filePath, config.cwd, config.runtime);
        if (redundantPrefixValidation) {
            return {
                success: false,
                error: redundantPrefixValidation.error,
            };
        }
        const pathValidation = (0, fileCommon_1.validatePathInCwd)(filePath, config.cwd, config.runtime);
        if (pathValidation) {
            return {
                success: false,
                error: pathValidation.error,
            };
        }
        // Use runtime's normalizePath method to resolve paths correctly for both local and SSH runtimes
        // This ensures path resolution uses runtime-specific semantics instead of Node.js path module
        const resolvedPath = config.runtime.normalizePath(filePath, config.cwd);
        // Check if file exists and get stats using runtime
        let fileStat;
        try {
            fileStat = await config.runtime.stat(resolvedPath, abortSignal);
        }
        catch (err) {
            if (err instanceof Runtime_1.RuntimeError) {
                return {
                    success: false,
                    error: err.message,
                };
            }
            throw err;
        }
        if (fileStat.isDirectory) {
            return {
                success: false,
                error: `Path is a directory, not a file: ${resolvedPath}`,
            };
        }
        const sizeValidation = (0, fileCommon_1.validateFileSize)(fileStat);
        if (sizeValidation) {
            return {
                success: false,
                error: sizeValidation.error,
            };
        }
        // Read file content using runtime helper
        let originalContent;
        try {
            originalContent = await (0, helpers_1.readFileString)(config.runtime, resolvedPath, abortSignal);
        }
        catch (err) {
            if (err instanceof Runtime_1.RuntimeError) {
                return {
                    success: false,
                    error: err.message,
                };
            }
            throw err;
        }
        const operationResult = await Promise.resolve(operation(originalContent));
        if (!operationResult.success) {
            return {
                success: false,
                error: operationResult.error,
                note: operationResult.note, // Pass through agent-only message
            };
        }
        // Write file using runtime helper
        try {
            await (0, helpers_1.writeFileString)(config.runtime, resolvedPath, operationResult.newContent, abortSignal);
        }
        catch (err) {
            if (err instanceof Runtime_1.RuntimeError) {
                return {
                    success: false,
                    error: err.message,
                };
            }
            throw err;
        }
        const diff = (0, fileCommon_1.generateDiff)(resolvedPath, originalContent, operationResult.newContent);
        return {
            success: true,
            diff,
            ...operationResult.metadata,
        };
    }
    catch (error) {
        if (error && typeof error === "object" && "code" in error) {
            const nodeError = error;
            if (nodeError.code === "ENOENT") {
                return {
                    success: false,
                    error: `File not found: ${filePath}`,
                };
            }
            if (nodeError.code === "EACCES") {
                return {
                    success: false,
                    error: `Permission denied: ${filePath}`,
                };
            }
        }
        const message = error instanceof Error ? error.message : String(error);
        return {
            success: false,
            error: `Failed to edit file: ${message}`,
        };
    }
}
//# sourceMappingURL=file_edit_operation.js.map