import { mkdtemp, rm, mkdir, writeFile, symlink, realpath } 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 { MAX_FILE_SIZE } from "@pocketcoder/shared/constants";
import { openDatabase, closeDatabase } from "../../db/database.js";
import { createProject } from "../../db/repositories/projects.js";
import { handleFsRead } from "../fs-read.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_read handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        // Use realpath to get the canonical path (handles macOS /var -> /private/var symlink)
        const rawTempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fs-read-test-"));
        tempDir = await realpath(rawTempDir);
        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 createFsReadRequest(path) {
        return {
            type: "fs_read",
            requestId: "req-1",
            sessionId: projectId,
            payload: { path },
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should read text file content", async () => {
        const content = 'import React from "react";\n\nexport default function App() {\n  return <div>Hello</div>;\n}\n';
        await mkdir(join(projectDir, "src"), { recursive: true });
        await writeFile(join(projectDir, "src", "app.tsx"), content);
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("src/app.tsx"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("fs_read_response");
        expect(resp.requestId).toBe("req-1");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("src/app.tsx");
        expect(resp.payload.content).toBe(content);
        expect(resp.payload.encoding).toBe("utf-8");
    });
    it("should include file metadata", async () => {
        const content = "# Hello World\n\nThis is a readme.";
        await writeFile(join(projectDir, "readme.md"), content);
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("readme.md"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeDefined();
        expect(resp.payload.size).toBe(Buffer.byteLength(content, "utf-8"));
        expect(resp.payload.mtime).toBeDefined();
        // mtime should be an ISO 8601 string
        expect(new Date(resp.payload.mtime).toISOString()).toBe(resp.payload.mtime);
    });
    it("should error for large files", async () => {
        // Create a file that exceeds MAX_FILE_SIZE
        // We'll create a sparse-like approach by writing just over the limit
        const largeContent = "x".repeat(MAX_FILE_SIZE + 1);
        await writeFile(join(projectDir, "large.txt"), largeContent);
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("large.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.FILE_TOO_LARGE);
        expect(resp.error.details).toBeDefined();
        expect(resp.error.details.limit).toBe(MAX_FILE_SIZE);
    }, 30000);
    it("should error for binary files", async () => {
        // Create a file with null bytes (binary content)
        const binaryContent = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00]);
        await writeFile(join(projectDir, "image.png"), binaryContent);
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("image.png"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.UNSUPPORTED_FORMAT);
    });
    it("should error for missing files", async () => {
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("nonexistent.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.FILE_NOT_FOUND);
    });
    it("should reject paths outside project", async () => {
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("../../../etc/passwd"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
    });
    it("should reject symlink escape", async () => {
        // Create a file outside the project
        const outsideDir = join(tempDir, "outside");
        await mkdir(outsideDir);
        await writeFile(join(outsideDir, "secret.txt"), "secret data");
        // Create a symlink inside the project pointing outside
        await symlink(join(outsideDir, "secret.txt"), join(projectDir, "escape-link.txt"));
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("escape-link.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.OUTSIDE_PROJECT_ROOT);
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "fs_read",
            requestId: "req-2",
            sessionId: "non-existent-project-id",
            payload: { path: "file.txt" },
        };
        const { responses, send } = createSendCollector();
        await handleFsRead(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should read empty files", async () => {
        await writeFile(join(projectDir, "empty.txt"), "");
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("empty.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.content).toBe("");
        expect(resp.payload.size).toBe(0);
    });
    it("should read files with UTF-8 content", async () => {
        const unicodeContent = "Hello 世界! 🌍 café résumé naïve";
        await writeFile(join(projectDir, "unicode.txt"), unicodeContent);
        const { responses, send } = createSendCollector();
        await handleFsRead(createFsReadRequest("unicode.txt"), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload.content).toBe(unicodeContent);
        expect(resp.payload.encoding).toBe("utf-8");
    });
});
//# sourceMappingURL=fs-read.test.js.map