"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 });
exports.testAdvancedFeatures = testAdvancedFeatures;
const client_1 = require("../../../src/agents/tools/ycmd/client");
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const serverManager_1 = require("../../../src/agents/tools/ycmd/serverManager");
const getLocations_1 = require("../../../src/agents/tools/ycmd/tools/getLocations");
async function testAdvancedFeatures() {
    console.log("🧪 Testing Advanced ycmd Features\n");
    const workspaceRoot = process.cwd();
    const testDir = path.join(workspaceRoot, "tests", "ycmd", "fixtures");
    if (!fs.existsSync(testDir)) {
        fs.mkdirSync(testDir, { recursive: true });
    }
    console.log("📁 Creating test files...\n");
    const tsFile = path.join(testDir, "test_imports.ts");
    const tsContent = `// TypeScript file with missing imports and issues
const fs = require('fs'); // Should suggest import
const path = require('path');

interface User {
    name: string;
    age: number;
    email?: string;
}

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

// Missing import for React (if available)
const component = React.createElement('div');

// Type error - missing property
const user: User = { name: 'Alice' }; // Missing age

// Unused variable
const unusedVar = 'test';

export { createUser };
`;
    const userLocations = await (0, getLocations_1.getLocations)({
        filepath: tsFile,
        fileContents: tsContent,
        searchString: "user",
    });
    const userLocation = userLocations.locations[0];
    const createUserLocations = await (0, getLocations_1.getLocations)({
        filepath: tsFile,
        fileContents: tsContent,
        searchString: "createUser",
    });
    const createUserLocation = createUserLocations.locations[0];
    const returnLocations = await (0, getLocations_1.getLocations)({
        filepath: tsFile,
        fileContents: tsContent,
        searchString: "return",
    });
    const returnLocation = returnLocations.locations[0];
    const { client: tsClient } = await serverManager_1.ycmdServerManager.setupClientAndNotifyFile({
        filepath: tsFile,
        fileContents: tsContent,
    });
    fs.writeFileSync(tsFile, tsContent);
    console.log(`✅ Created ${tsFile}`);
    const jsFile = path.join(testDir, "test_format.js");
    const jsContent = `// JavaScript file with formatting issues
function   badlyFormatted(  a,b,   c )
{
return a+b+c;
}

const obj={a:1,b:2,c:3};

if(true){
console.log("badly formatted");
}
`;
    fs.writeFileSync(jsFile, jsContent);
    console.log(`✅ Created ${jsFile}\n`);
    console.log("🔍 TESTING DIAGNOSTICS AND FIXITS\n");
    try {
        console.log("1. Getting diagnostics for TypeScript file...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const brokenCode = tsContent.replace("return { name", "return { nade");
        fs.writeFileSync(tsFile, brokenCode);
        const { client } = await serverManager_1.ycmdServerManager.setupClientAndNotifyFile({
            filepath: tsFile,
            fileContents: brokenCode,
        });
        const diagnostics = await client.getDiagnostics(tsFile, tsContent, filetypes);
        console.log(`✅ Found ${diagnostics.length} diagnostics`);
        for (let i = 0; i < diagnostics.length; i++) {
            const diag = diagnostics[i];
            console.log(`   Diagnostic ${i + 1}:`);
            console.log(`   - Line ${diag.location.line_num}, Col ${diag.location.column_num}`);
            console.log(`   - Kind: ${diag.kind}`);
            console.log(`   - Text: ${diag.text}`);
            if (diag.fixit_available) {
                console.log(`   - ✅ Fixit available!`);
                try {
                    const fixitResult = await client.refactorFixIt(tsFile, diag.location.line_num, diag.location.column_num, tsContent, filetypes, 0);
                    console.log(`   - ✅ Fixit applied successfully`);
                    console.log(`   - Result:`, JSON.stringify(fixitResult, null, 4));
                }
                catch (fixitError) {
                    console.log(`   - ❌ Fixit failed: ${fixitError.message}`);
                }
            }
            else {
                console.log(`   - ❌ No fixit available`);
            }
            console.log("");
        }
    }
    catch (error) {
        console.log(`❌ Diagnostics failed: ${error.message}\n`);
    }
    console.log("🔧 TESTING AUTO-IMPORT FEATURES\n");
    try {
        console.log("2. Testing RefactorOrganizeImports...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const { client } = await serverManager_1.ycmdServerManager.setupClientAndNotifyFile({
            filepath: tsFile,
            fileContents: jsContent,
        });
        const organizeResult = await client.refactorOrganizeImports(tsFile, 1, 1, tsContent, filetypes);
        console.log("✅ RefactorOrganizeImports succeeded");
        console.log("Result:", JSON.stringify(organizeResult, null, 2));
    }
    catch (error) {
        console.log(`❌ RefactorOrganizeImports failed: ${error.message}`);
    }
    try {
        console.log("\n3. Testing completions for import suggestions...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const completionRequest = {
            filepath: tsFile,
            line_num: 15,
            column_num: 15,
            file_data: {
                [tsFile]: {
                    contents: tsContent,
                    filetypes,
                },
            },
        };
        const completionResponse = await tsClient.getCompletions(completionRequest);
        const completions = completionResponse.completions;
        console.log(`✅ Found ${completions.length} completions`);
        const importCompletions = completions.filter((c) => c.insertion_text?.includes("import") ||
            c.detailed_info?.includes("import") ||
            c.kind?.includes("import"));
        if (importCompletions.length > 0) {
            console.log(`✅ Found ${importCompletions.length} import-related completions:`);
            importCompletions.forEach((comp, i) => {
                console.log(`   ${i + 1}. ${comp.insertion_text} (${comp.kind})`);
                if (comp.detailed_info) {
                    console.log(`      Info: ${comp.detailed_info}`);
                }
            });
        }
        else {
            console.log("❌ No import-related completions found");
        }
    }
    catch (error) {
        console.log(`❌ Completions test failed: ${error.message}`);
    }
    console.log("\n🔄 TESTING ADVANCED REFACTORING\n");
    try {
        console.log("4. Testing RefactorRename...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const renameResult = await tsClient.refactorRename(tsFile, userLocation.line, userLocation.column, tsContent, filetypes, "buildUser");
        console.log("✅ RefactorRename succeeded");
        console.log("Result:", JSON.stringify(renameResult, null, 2));
    }
    catch (error) {
        console.log(`❌ RefactorRename failed: ${error.message}`);
    }
    try {
        console.log("\n5. Testing RefactorExtractMethod...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const extractResult = await tsClient.refactorExtractMethod(tsFile, returnLocation.line, returnLocation.column, tsContent, filetypes);
        console.log("✅ RefactorExtractMethod succeeded");
        console.log("Result:", JSON.stringify(extractResult, null, 2));
    }
    catch (error) {
        console.log(`❌ RefactorExtractMethod failed: ${error.message}`);
    }
    console.log("\n📋 TESTING CODE INTELLIGENCE\n");
    try {
        console.log("6. Testing GetType...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const typeResult = await tsClient.getSignatureHelp(tsFile, userLocation.line, userLocation.column, tsContent, filetypes);
        console.log("✅ GetType succeeded");
        console.log("Result:", JSON.stringify(typeResult, null, 2));
    }
    catch (error) {
        console.log(`❌ GetType failed: ${error.message}`);
    }
    try {
        console.log("\n7. Testing GoToDefinition...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const defResult = await tsClient.goToDefinition(tsFile, userLocation.line, userLocation.column, tsContent, filetypes);
        console.log("✅ GoToDefinition succeeded");
        console.log("Result:", JSON.stringify(defResult, null, 2));
    }
    catch (error) {
        console.log(`❌ GoToDefinition failed: ${error.message}`);
    }
    try {
        console.log("\n8. Testing GoToReferences...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const refsResult = await tsClient.goToReferences(tsFile, createUserLocation.line, createUserLocation.column, tsContent, filetypes);
        console.log("✅ GoToReferences succeeded");
        console.log("Result:", JSON.stringify(refsResult, null, 2));
    }
    catch (error) {
        console.log(`❌ GoToReferences failed: ${error.message}`);
    }
    console.log("\n🔍 TESTING COMMAND DISCOVERY\n");
    try {
        console.log("9. Testing command discovery...");
        const filetypes = (0, client_1.getFileTypes)(tsFile);
        const commands = await tsClient.getRefactorCommands(tsFile, 9, 10, tsContent, filetypes);
        console.log("✅ Command discovery succeeded");
        console.log(`Found ${commands.length} available commands:`);
        commands.forEach((cmd, i) => {
            console.log(`   ${i + 1}. ${cmd}`);
        });
    }
    catch (error) {
        console.log(`❌ Command discovery failed: ${error.message}`);
    }
    console.log("\n🔄 TESTING EDGE CASES\n");
    const syntaxErrorFile = path.join(testDir, "syntax_error.ts");
    const syntaxErrorContent = `
function broken(
    // Missing closing parenthesis and body
`;
    fs.writeFileSync(syntaxErrorFile, syntaxErrorContent);
    try {
        console.log("10. Testing refactoring on file with syntax errors...");
        const filetypes = (0, client_1.getFileTypes)(syntaxErrorFile);
        const syntaxRefactorResult = await tsClient.refactorRename(syntaxErrorFile, 2, 10, syntaxErrorContent, filetypes, "fixed");
        console.log("⚠️ Syntax error refactor succeeded (unexpected)");
        console.log("Result:", JSON.stringify(syntaxRefactorResult, null, 2));
    }
    catch (error) {
        console.log(`✅ Syntax error refactor correctly failed: ${error.message}`);
    }
    console.log("\n🧹 Cleaning up test files...");
    try {
        fs.unlinkSync(tsFile);
        fs.unlinkSync(jsFile);
        fs.unlinkSync(syntaxErrorFile);
        console.log("✅ Test files cleaned up");
    }
    catch (error) {
        console.log("⚠️ Could not clean up all test files");
    }
    console.log("\n🎉 Advanced features testing complete!");
    process.exit(0);
}
if (require.main === module) {
    testAdvancedFeatures().catch((error) => {
        console.error("Test failed:", error);
        process.exit(1);
    });
}
//# sourceMappingURL=test_advanced_features.js.map