"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const ycmd_1 = require("../../../src/agents/tools/ycmd");
const serverManager_1 = require("../../../src/agents/tools/ycmd/serverManager");
const client_1 = require("../../../src/agents/tools/ycmd/client");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
async function wait(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
async function testDiagnosticsWithFileChanges() {
    console.log("🔧 Testing ycmd diagnostics with proper file change notifications...");
    try {
        console.log("Starting ycmd server...");
        const startResult = await (0, ycmd_1.ycmdStart)({
            workspaceRoot: process.cwd(),
            logLevel: "debug",
        });
        if (!startResult.success) {
            throw new Error(`Failed to start server: ${startResult.message}`);
        }
        console.log("✅ ycmd server started");
        console.log("⏳ Waiting for server initialization...");
        await wait(2000);
        const testDir = path.join(process.cwd(), "tests/ycmd/fixtures");
        const testFile = path.join(testDir, "file_change_test.ts");
        if (!fs.existsSync(testDir)) {
            fs.mkdirSync(testDir, { recursive: true });
        }
        const serverInfo = serverManager_1.ycmdServerManager.getServerInfo();
        if (!serverInfo) {
            throw new Error("Failed to get server info");
        }
        const client = new client_1.YcmdClient(serverInfo);
        const filetypes = (0, client_1.getFileTypes)(testFile);
        console.log("📝 Step 1: Creating valid TypeScript file...");
        const validContent = `interface User {
    name: string;
    age: number;
}

function createUser(name: string, age: number): User {
    return { name, age };
}

export { createUser };`;
        fs.writeFileSync(testFile, validContent);
        console.log("🔔 Notifying ycmd about initial file...");
        await client.notifyFileEvent("BufferVisit", testFile, validContent, filetypes);
        await wait(100);
        await client.notifyFileEvent("FileReadyToParse", testFile, validContent, filetypes);
        await wait(500);
        console.log("🔍 Testing diagnostics on valid file...");
        let diagnostics = await (0, ycmd_1.ycmdDiagnostics)({
            filepath: testFile,
            line: 1,
            column: 1,
        });
        console.log("Valid file diagnostics:", JSON.stringify(diagnostics, null, 2));
        console.log("📝 Step 2: Modifying file to introduce TypeScript errors...");
        const errorContent = `interface User {
    name: string;
    age: number;
}

function createUser(name: string, age: number): User {
    // ERROR: Missing 'age' property - should cause TypeScript error
    return { name };
}

// ERROR: Using undefined variable - should cause TypeScript error
console.log(undefinedVariable);

// ERROR: Type mismatch - missing required property - should cause TypeScript error
const user: User = { name: 'Alice' };

export { createUser };`;
        fs.writeFileSync(testFile, errorContent);
        console.log("🔔 Step 3: Notifying ycmd about file changes...");
        console.log("  📤 Unloading old file version...");
        await client.notifyFileEvent("BufferUnload", testFile, validContent, filetypes);
        await wait(200);
        console.log("  📥 Loading new file version...");
        await client.notifyFileEvent("BufferVisit", testFile, errorContent, filetypes);
        await wait(100);
        await client.notifyFileEvent("FileReadyToParse", testFile, errorContent, filetypes);
        await wait(100);
        console.log("  ⏳ Waiting for TSServer to process changes...");
        await wait(2000);
        console.log("🔍 Step 4: Testing diagnostics on modified file...");
        diagnostics = await (0, ycmd_1.ycmdDiagnostics)({
            filepath: testFile,
            fileContents: errorContent,
            line: 1,
            column: 1,
        });
        console.log("Modified file diagnostics:", JSON.stringify(diagnostics, null, 2));
        if (diagnostics.success &&
            diagnostics.diagnostics &&
            diagnostics.diagnostics.length > 0) {
            console.log(`🎉 SUCCESS: Found ${diagnostics.diagnostics.length} diagnostic(s)!`);
            diagnostics.diagnostics.forEach((diag, index) => {
                console.log(`  ${index + 1}. Line ${diag.location.line}: ${diag.text}`);
            });
        }
        else {
            console.log("❌ Still no diagnostics found. Trying alternative approaches...");
            console.log("🎯 Testing specific error locations...");
            const errorLines = [8, 11, 14];
            for (const line of errorLines) {
                console.log(`  Testing line ${line}...`);
                const lineDiagnostics = await (0, ycmd_1.ycmdDiagnostics)({
                    filepath: testFile,
                    fileContents: errorContent,
                    line,
                    column: 1,
                });
                console.log(`  Line ${line} diagnostics:`, JSON.stringify(lineDiagnostics, null, 2));
                if (lineDiagnostics.success &&
                    lineDiagnostics.diagnostics &&
                    lineDiagnostics.diagnostics.length > 0) {
                    console.log(`  🎉 Found diagnostics at line ${line}!`);
                    break;
                }
            }
            console.log("🔧 Trying direct client diagnostic check...");
            try {
                const directDiagnostics = await client.getDiagnostics(testFile, errorContent, filetypes, 1, 1);
                console.log("Direct client diagnostics:", JSON.stringify(directDiagnostics, null, 2));
                if (directDiagnostics.length > 0) {
                    console.log(`🎉 SUCCESS via direct client: Found ${directDiagnostics.length} diagnostic(s)!`);
                    directDiagnostics.forEach((diag, index) => {
                        console.log(`  ${index + 1}. Line ${diag.location.line_num}: ${diag.text}`);
                    });
                }
            }
            catch (error) {
                console.log("Direct client diagnostics failed:", error.message);
            }
        }
        fs.unlinkSync(testFile);
        console.log("✅ Test completed");
    }
    catch (error) {
        console.error("❌ Test failed:", error.message);
        console.error("Stack trace:", error.stack);
        process.exit(1);
    }
}
testDiagnosticsWithFileChanges();
//# sourceMappingURL=test_diagnostics_file_changes.js.map