import { mkdtemp, rm, mkdir, writeFile, readFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { ErrorCode } from "@pocketcoder/shared/constants";
import { openDatabase, closeDatabase } from "../../db/database.js";
import { createProject } from "../../db/repositories/projects.js";
import { handleFsReplace } from "../fs-replace.js";
// Suppress logger output in tests
vi.mock("../../utils/logger.js", () => ({
    logger: {
        debug: vi.fn(),
        info: vi.fn(),
        warn: vi.fn(),
        error: vi.fn(),
    },
}));
describe("fs_replace handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fs-replace-test-"));
        projectDir = join(tempDir, "project");
        dbPath = join(tempDir, "daemon.db");
        await mkdir(projectDir);
        closeDatabase();
        openDatabase(dbPath);
        const project = createProject("test-project", projectDir);
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createFsReplaceRequest(find, replace, options) {
        return {
            type: "fs_replace",
            requestId: "req-1",
            sessionId: projectId,
            payload: {
                find,
                replace,
                ...options,
            },
        };
    }
    function createSendCollector() {
        const messages = [];
        const send = (msg) => {
            messages.push(msg);
        };
        return { messages, send };
    }
    it("should find and replace text", async () => {
        await writeFile(join(projectDir, "file.txt"), "Hello world\nHello again");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("Hello", "Hi"), send);
        // Should have fs_changed event + response
        const response = messages.find((m) => m.type === "fs_replace_response");
        expect(response).toBeDefined();
        expect(response.error).toBeUndefined();
        expect(response.payload).toBeDefined();
        expect(response.payload.totalReplacements).toBe(2);
        expect(response.payload.filesModified).toHaveLength(1);
        expect(response.payload.filesModified[0].path).toBe("file.txt");
        expect(response.payload.filesModified[0].replacements).toBe(2);
        // Verify file was actually modified
        const content = await readFile(join(projectDir, "file.txt"), "utf-8");
        expect(content).toBe("Hi world\nHi again");
    });
    it("should filter by glob", async () => {
        await writeFile(join(projectDir, "app.ts"), "const x = 1;");
        await writeFile(join(projectDir, "app.js"), "const x = 2;");
        await writeFile(join(projectDir, "readme.md"), "const x = 3;");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("const", "let", { glob: "*.ts" }), send);
        const response = messages.find((m) => m.type === "fs_replace_response");
        expect(response.error).toBeUndefined();
        expect(response.payload.totalReplacements).toBe(1);
        expect(response.payload.filesModified).toHaveLength(1);
        expect(response.payload.filesModified[0].path).toBe("app.ts");
        // Verify only the .ts file was modified
        expect(await readFile(join(projectDir, "app.ts"), "utf-8")).toBe("let x = 1;");
        expect(await readFile(join(projectDir, "app.js"), "utf-8")).toBe("const x = 2;");
        expect(await readFile(join(projectDir, "readme.md"), "utf-8")).toBe("const x = 3;");
    });
    it("should return replacement counts per file", async () => {
        await mkdir(join(projectDir, "src"));
        await writeFile(join(projectDir, "src", "utils.ts"), "foo bar foo baz foo");
        await writeFile(join(projectDir, "src", "helpers.ts"), "foo qux foo");
        await writeFile(join(projectDir, "other.ts"), "no matches here");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("foo", "replaced"), send);
        const response = messages.find((m) => m.type === "fs_replace_response");
        expect(response.error).toBeUndefined();
        expect(response.payload.totalReplacements).toBe(5);
        expect(response.payload.filesModified).toHaveLength(2);
        const utils = response.payload.filesModified.find((f) => f.path.includes("utils.ts"));
        const helpers = response.payload.filesModified.find((f) => f.path.includes("helpers.ts"));
        expect(utils).toBeDefined();
        expect(utils.replacements).toBe(3);
        expect(helpers).toBeDefined();
        expect(helpers.replacements).toBe(2);
    });
    it("should emit fs_changed events", async () => {
        await writeFile(join(projectDir, "file1.txt"), "target text");
        await writeFile(join(projectDir, "file2.txt"), "target text");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("target", "replaced"), send);
        const fsChanged = messages.find((m) => m.type === "fs_changed");
        expect(fsChanged).toBeDefined();
        expect(fsChanged.type).toBe("fs_changed");
        expect(fsChanged.sessionId).toBe(projectId);
        expect(fsChanged.payload.seq).toBeGreaterThan(0);
        expect(fsChanged.payload.changes).toHaveLength(2);
        expect(fsChanged.payload.changes.every((c) => c.kind === "modify")).toBe(true);
    });
    it("should handle case sensitivity", async () => {
        await writeFile(join(projectDir, "test.txt"), "Hello hello HELLO");
        // Case insensitive (default)
        const { messages: m1, send: s1 } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("hello", "hi"), s1);
        const r1 = m1.find((m) => m.type === "fs_replace_response");
        expect(r1.payload.totalReplacements).toBe(3);
        // Reset file
        await writeFile(join(projectDir, "test.txt"), "Hello hello HELLO");
        // Case sensitive
        const { messages: m2, send: s2 } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("hello", "hi", { caseSensitive: true }), s2);
        const r2 = m2.find((m) => m.type === "fs_replace_response");
        expect(r2.payload.totalReplacements).toBe(1);
    });
    it("should support regex mode", async () => {
        await writeFile(join(projectDir, "code.ts"), "const foo = 1;\nconst bar = 2;\nlet baz = 3;");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("const (\\w+)", "let $1", { regex: true }), send);
        const response = messages.find((m) => m.type === "fs_replace_response");
        expect(response.error).toBeUndefined();
        expect(response.payload.totalReplacements).toBe(2);
        const content = await readFile(join(projectDir, "code.ts"), "utf-8");
        expect(content).toBe("let foo = 1;\nlet bar = 2;\nlet baz = 3;");
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "fs_replace",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { find: "test", replace: "replaced" },
        };
        const { messages, send } = createSendCollector();
        await handleFsReplace(msg, send);
        expect(messages).toHaveLength(1);
        const response = messages[0];
        expect(response.error).toBeDefined();
        expect(response.error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should return error for empty find string", async () => {
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("", "replacement"), send);
        expect(messages).toHaveLength(1);
        const response = messages[0];
        expect(response.error).toBeDefined();
        expect(response.error.code).toBe(ErrorCode.QUERY_TOO_SHORT);
    });
    it("should return error for invalid regex", async () => {
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("[invalid(", "replacement", { regex: true }), send);
        expect(messages).toHaveLength(1);
        const response = messages[0];
        expect(response.error).toBeDefined();
        expect(response.error.code).toBe(ErrorCode.INVALID_REGEX);
    });
    it("should return empty results when no matches found", async () => {
        await writeFile(join(projectDir, "file.txt"), "nothing here");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("nonexistent_xyz", "replacement"), send);
        // Should only have response (no fs_changed since nothing was modified)
        expect(messages).toHaveLength(1);
        const response = messages[0];
        expect(response.error).toBeUndefined();
        expect(response.payload.totalReplacements).toBe(0);
        expect(response.payload.filesModified).toHaveLength(0);
    });
    it("should exclude node_modules and .git", async () => {
        await mkdir(join(projectDir, "node_modules", "pkg"), { recursive: true });
        await writeFile(join(projectDir, "node_modules", "pkg", "index.js"), "const target = 1;");
        await mkdir(join(projectDir, ".git", "objects"), { recursive: true });
        await writeFile(join(projectDir, ".git", "config"), "const target = 2;");
        await writeFile(join(projectDir, "src.ts"), "const target = 3;");
        const { messages, send } = createSendCollector();
        await handleFsReplace(createFsReplaceRequest("target", "replaced"), send);
        const response = messages.find((m) => m.type === "fs_replace_response");
        expect(response.error).toBeUndefined();
        expect(response.payload.totalReplacements).toBe(1);
        expect(response.payload.filesModified).toHaveLength(1);
        expect(response.payload.filesModified[0].path).toBe("src.ts");
    });
});
//# sourceMappingURL=fs-replace.test.js.map