import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { join } from "path";
import { mkdir, writeFile, rm, readFile } from "fs/promises";
import { tmpdir } from "os";
import { runAIVerification, quickAICheck, loadAIVerifyConfig, generateAIVerifyConfig, formatVerificationReport, } from "../../../scanners/ai-code/index.js";
describe("ai-code module exports", () => {
    it("exports runAIVerification", () => {
        expect(typeof runAIVerification).toBe("function");
    });
    it("exports quickAICheck", () => {
        expect(typeof quickAICheck).toBe("function");
    });
    it("exports loadAIVerifyConfig", () => {
        expect(typeof loadAIVerifyConfig).toBe("function");
    });
    it("exports generateAIVerifyConfig", () => {
        expect(typeof generateAIVerifyConfig).toBe("function");
    });
    it("exports formatVerificationReport", () => {
        expect(typeof formatVerificationReport).toBe("function");
    });
});
describe("ai-code integration", () => {
    let testDir;
    beforeEach(async () => {
        testDir = join(tmpdir(), `ai-code-integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
        await mkdir(testDir, { recursive: true });
        await writeFile(join(testDir, "package.json"), JSON.stringify({
            name: "test-project",
            dependencies: { react: "^18.0.0" },
        }));
    });
    afterEach(async () => {
        await rm(testDir, { recursive: true, force: true });
    });
    describe("runAIVerification", () => {
        it("analyzes a project with clean code", async () => {
            await writeFile(join(testDir, "clean.ts"), `
function add(a: number, b: number): number {
  return a + b;
}

export { add };
`);
            const result = await runAIVerification(testDir);
            expect(result.success).toBe(true);
            expect(result.filesAnalyzed).toBe(1);
            expect(result.score.overallScore).toBeGreaterThan(50);
        });
        it("detects AI patterns", async () => {
            await writeFile(join(testDir, "ai-generated.ts"), `
// Generated by ChatGPT
// @cursor-ai
function example() {
  // TODO: implement this logic here
  return null;
}
`);
            const result = await runAIVerification(testDir);
            expect(result.success).toBe(true);
            expect(result.indicators.length).toBeGreaterThan(0);
            expect(result.summary.aiLikelyChanges).toBeGreaterThan(0);
        });
        it("detects hallucinations", async () => {
            await writeFile(join(testDir, "hallucinated.ts"), `
import { x } from "./nonexistent-module";
import fake from "react-native-awesome-button";
`);
            const result = await runAIVerification(testDir);
            expect(result.success).toBe(true);
            expect(result.hallucinations.length).toBeGreaterThan(0);
        });
        it("respects specific files option", async () => {
            await writeFile(join(testDir, "a.ts"), "const a = 1;");
            await writeFile(join(testDir, "b.ts"), "const b = 2;");
            const result = await runAIVerification(testDir, {
                files: ["a.ts"],
            });
            expect(result.filesAnalyzed).toBe(1);
        });
    });
    describe("quickAICheck", () => {
        it("checks a single file", async () => {
            await writeFile(join(testDir, "test.ts"), `
// Generated by AI
function test() {
  return true;
}
`);
            const result = await quickAICheck(join(testDir, "test.ts"), testDir);
            expect(result.aiLikelihood).toBeGreaterThan(0);
            expect(result.indicators.length).toBeGreaterThan(0);
        });
        it("returns low likelihood for clean code", async () => {
            await writeFile(join(testDir, "clean.ts"), `
function add(a: number, b: number): number {
  return a + b;
}
`);
            const result = await quickAICheck(join(testDir, "clean.ts"), testDir);
            expect(result.aiLikelihood).toBe(0);
            expect(result.requiresReview).toBe(false);
        });
    });
    describe("loadAIVerifyConfig", () => {
        it("returns null for non-existent config", async () => {
            const config = await loadAIVerifyConfig(testDir);
            expect(config).toBeNull();
        });
        it("loads YAML config", async () => {
            const vasperaDir = join(testDir, ".vaspera");
            await mkdir(vasperaDir, { recursive: true });
            await writeFile(join(vasperaDir, "ai-verify.yaml"), `
detection:
  checkPatterns: true
review:
  requireForConfidence: high
  autoApproveBelow: 20
`);
            const config = await loadAIVerifyConfig(testDir);
            expect(config).not.toBeNull();
            expect(config?.detection?.checkPatterns).toBe(true);
            expect(config?.review?.requireForConfidence).toBe("high");
            expect(config?.review?.autoApproveBelow).toBe(20);
        });
        it("loads JSON config", async () => {
            const vasperaDir = join(testDir, ".vaspera");
            await mkdir(vasperaDir, { recursive: true });
            await writeFile(join(vasperaDir, "ai-verify.json"), JSON.stringify({
                detection: { checkPatterns: false },
                review: { autoApproveBelow: 50 },
            }));
            const config = await loadAIVerifyConfig(testDir);
            expect(config).not.toBeNull();
            expect(config?.detection?.checkPatterns).toBe(false);
        });
    });
    describe("generateAIVerifyConfig", () => {
        it("creates config file", async () => {
            const configPath = await generateAIVerifyConfig(testDir);
            expect(configPath).toContain("ai-verify.yaml");
            const content = await readFile(configPath, "utf-8");
            expect(content).toContain("detection");
            expect(content).toContain("hallucination");
            expect(content).toContain("review");
        });
    });
    describe("formatVerificationReport", () => {
        it("formats a verification result", () => {
            const result = {
                success: true,
                filesAnalyzed: 10,
                changesScored: [],
                hallucinations: [],
                indicators: [],
                summary: {
                    totalChanges: 10,
                    aiLikelyChanges: 2,
                    requiresReview: 1,
                    hallucinationsFound: 0,
                    averageConfidence: 25.5,
                },
                score: {
                    detectionScore: 85,
                    hallucinationScore: 100,
                    reviewScore: 90,
                    overallScore: 92,
                },
                duration: 1234,
            };
            const report = formatVerificationReport(result);
            expect(report).toContain("AI Code Verification Report");
            expect(report).toContain("Files analyzed: 10");
            expect(report).toContain("Detection Score: 85/100");
            expect(report).toContain("Overall Score: 92/100");
        });
        it("includes hallucinations in report", () => {
            const result = {
                success: true,
                filesAnalyzed: 5,
                changesScored: [],
                hallucinations: [
                    {
                        type: "nonexistent_import",
                        location: { file: "test.ts", line: 1 },
                        severity: "high",
                        description: "Import does not exist",
                        actual: "./missing",
                        suggestion: "Create the file or fix the import",
                    },
                ],
                indicators: [],
                summary: {
                    totalChanges: 5,
                    aiLikelyChanges: 1,
                    requiresReview: 1,
                    hallucinationsFound: 1,
                    averageConfidence: 30,
                },
                score: {
                    detectionScore: 70,
                    hallucinationScore: 85,
                    reviewScore: 80,
                    overallScore: 80,
                },
                duration: 500,
            };
            const report = formatVerificationReport(result);
            expect(report).toContain("Hallucinations:");
            expect(report).toContain("Import does not exist");
        });
    });
});
//# sourceMappingURL=index.test.js.map