import { readFile, writeFile } from "node:fs/promises";
import { resolveWorkspacePath } from "../safety/guardrails.js";
import { replaceWithCascade } from "./edit-file-replacers.js";
import { expectNonEmptyString } from "./helpers.js";
function expectString(input, key) {
    const value = input[key];
    if (typeof value !== "string") {
        throw new Error(`Input "${key}" must be a string.`);
    }
    return value;
}
export function createEditFileTool(options, hooks) {
    return {
        name: "edit_file",
        description: "Replace exactly one instance of old_string with new_string in a file.",
        inputSchema: {
            type: "object",
            properties: {
                path: {
                    type: "string",
                    description: "Path to file relative to workspace root.",
                },
                old_string: {
                    type: "string",
                    description: "Text to replace (must match the file uniquely).",
                },
                new_string: {
                    type: "string",
                    description: "Replacement text.",
                },
            },
            required: ["path", "old_string", "new_string"],
            additionalProperties: false,
        },
        execute: async (input) => {
            const requestedPath = expectNonEmptyString(input, "path");
            const oldString = expectNonEmptyString(input, "old_string");
            const newString = expectString(input, "new_string");
            const filePath = resolveWorkspacePath(requestedPath, options.workspaceRoot);
            const current = await readFile(filePath, "utf8");
            let updated;
            try {
                updated = replaceWithCascade(current, oldString, newString);
            }
            catch (error) {
                const detail = error.message;
                throw new Error(`${detail} (file: "${requestedPath}")`);
            }
            await writeFile(filePath, updated, "utf8");
            let suffix = "";
            if (hooks?.afterEdit) {
                const result = await hooks.afterEdit(filePath, updated);
                if (typeof result === "string" && result.length > 0) {
                    suffix = `\n\n${result}`;
                }
            }
            return `Updated "${requestedPath}" successfully.${suffix}`;
        },
    };
}
//# sourceMappingURL=edit-file.js.map