import { z } from "zod";
import { createToolFactory, PermissionLevel, ToolCategory, ToolExecutionError, } from "../types.js";
/**
 * Edit tool - Performs exact string replacements in files.
 */
export const editToolFactory = createToolFactory("edit", (services) => ({
    description: "Performs exact string replacements in files.",
    category: ToolCategory.FILE,
    defaultPermission: PermissionLevel.ALLOW,
    inputSchema: z.object({
        file_path: z.string().describe("Relative path to file"),
        old_string: z.string().describe("Text to replace"),
        new_string: z.string().describe("Text to replace with"),
        replace_all: z
            .boolean()
            .optional()
            .default(false)
            .describe("Replace all occurrences (default: false)"),
    }),
    execute: async ({ file_path, old_string, new_string, replace_all }) => {
        try {
            const content = await services.appShell.readFile(file_path);
            let newContent;
            if (replace_all) {
                newContent = content.split(old_string).join(new_string);
            }
            else {
                const index = content.indexOf(old_string);
                if (index === -1) {
                    throw new Error(`String not found in file: ${old_string}`);
                }
                const secondIndex = content.indexOf(old_string, index + 1);
                if (secondIndex !== -1) {
                    throw new Error("String is not unique in file. Use replace_all=true or provide more context.");
                }
                newContent =
                    content.substring(0, index) +
                        new_string +
                        content.substring(index + old_string.length);
            }
            await services.appShell.writeFile(file_path, newContent);
            return {
                success: true,
                message: `File edited: ${file_path}`,
                replacements: replace_all ? content.split(old_string).length - 1 : 1,
            };
        }
        catch (error) {
            if (!(error instanceof Error)) {
                throw new Error("Failed to edit file: Unknown error");
            }
            throw new ToolExecutionError(`Failed to edit file: ${error.message}`, {
                toolName: "",
                input: {},
                context: {},
                severity: "warn",
            });
        }
    },
    getSummary: (_input, output) => {
        const count = output.replacements ?? 1;
        return {
            output: `${count} replacement${count === 1 ? "" : "s"}`,
        };
    },
}));
//# sourceMappingURL=edit.js.map