"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.activate = activate;
exports.deactivate = deactivate;
const vscode = __importStar(require("vscode"));
const AxionAIViewProvider_1 = require("./providers/AxionAIViewProvider");
const FileManager_1 = require("./services/FileManager");
const ChangeTracker_1 = require("./services/ChangeTracker");
const CodeQualityService_1 = require("./services/CodeQualityService");
const AIService_1 = require("./services/AIService");
const AIModels_1 = require("./models/AIModels");
let provider;
let codeQualityService;
let aiService;
function activate(context) {
    console.log('⚡ Axion AI is now active!');
    const fileManager = new FileManager_1.FileManager();
    const changeTracker = new ChangeTracker_1.ChangeTracker();
    aiService = new AIService_1.AIService();
    codeQualityService = new CodeQualityService_1.CodeQualityService(aiService, fileManager);
    provider = new AxionAIViewProvider_1.AxionAIViewProvider(context.extensionUri, context, fileManager, changeTracker);
    // Register webview provider
    context.subscriptions.push(vscode.window.registerWebviewViewProvider('axion-ai.chatView', provider, {
        webviewOptions: {
            retainContextWhenHidden: true
        }
    }));
    // Register commands
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.openPanel', () => {
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.newChat', () => {
        provider.newChat();
    }));
    // Code action commands
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.explainCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        if (!text && selection.isEmpty) {
            vscode.window.showWarningMessage('Please select code to explain');
            return;
        }
        await provider.sendMessage(`Explain this code:\n\`\`\`\n${text || editor.document.getText()}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.refactorCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        if (!text && selection.isEmpty) {
            vscode.window.showWarningMessage('Please select code to refactor');
            return;
        }
        await provider.sendMessage(`Refactor and improve this code:\n\`\`\`${editor.document.languageId}\n${text || editor.document.getText()}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.generateCode', async () => {
        const input = await vscode.window.showInputBox({
            prompt: 'What code would you like to generate?',
            placeHolder: 'e.g., Create a function to sort an array'
        });
        if (input) {
            await provider.sendMessage(`Generate code: ${input}`);
            vscode.commands.executeCommand('axion-ai.chatView.focus');
        }
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.fixBugs', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        const code = text || editor.document.getText();
        // Use code quality service for intelligent bug detection
        const model = (0, AIModels_1.getModelById)('claude-sonnet-4') || (0, AIModels_1.getModelById)('gpt-4o') || null;
        if (model && aiService.hasApiKey(model.provider)) {
            vscode.window.showInformationMessage('Analyzing code for bugs...');
            const bugs = await codeQualityService.detectBugs(model, code, editor.document.languageId);
            if (bugs.length > 0) {
                const bugReport = bugs.map(b => `[${b.severity.toUpperCase()}] ${b.message}${b.suggestion ? `\nSuggestion: ${b.suggestion}` : ''}`).join('\n\n');
                await provider.sendMessage(`Found ${bugs.length} potential bug(s). Analyzing and fixing:\n\n${bugReport}\n\nCode:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
            }
            else {
                await provider.sendMessage(`Analyzed code for bugs. No obvious bugs detected. Reviewing code for potential issues:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
            }
        }
        else {
            await provider.sendMessage(`Find and fix bugs in this code:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
        }
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.optimizeCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        const code = text || editor.document.getText();
        // Use code quality service for intelligent optimization suggestions
        const model = (0, AIModels_1.getModelById)('claude-sonnet-4') || (0, AIModels_1.getModelById)('gpt-4o') || null;
        if (model && aiService.hasApiKey(model.provider)) {
            vscode.window.showInformationMessage('Analyzing code for optimizations...');
            const optimizations = await codeQualityService.suggestOptimizations(model, code, editor.document.languageId);
            if (optimizations.length > 0) {
                const optReport = optimizations.map((opt, i) => `${i + 1}. ${opt}`).join('\n');
                await provider.sendMessage(`Found ${optimizations.length} optimization opportunity(ies):\n\n${optReport}\n\nOptimizing code:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
            }
            else {
                await provider.sendMessage(`Optimizing this code for performance:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
            }
        }
        else {
            await provider.sendMessage(`Optimize this code for performance:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
        }
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.addComments', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        await provider.sendMessage(`Add comprehensive comments to this code:\n\`\`\`${editor.document.languageId}\n${text || editor.document.getText()}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.writeTests', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const text = editor.document.getText();
        await provider.sendMessage(`Write comprehensive tests for this code:\n\`\`\`${editor.document.languageId}\n${text}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.translateCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const languages = ['TypeScript', 'JavaScript', 'Python', 'Java', 'C++', 'C#', 'Go', 'Rust'];
        const targetLang = await vscode.window.showQuickPick(languages, {
            placeHolder: 'Select target language'
        });
        if (targetLang) {
            const selection = editor.selection;
            const text = editor.document.getText(selection.isEmpty ? undefined : selection);
            await provider.sendMessage(`Translate this code to ${targetLang}:\n\`\`\`${editor.document.languageId}\n${text || editor.document.getText()}\n\`\`\``);
            vscode.commands.executeCommand('axion-ai.chatView.focus');
        }
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.documentCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        await provider.sendMessage(`Generate documentation for this code:\n\`\`\`${editor.document.languageId}\n${text || editor.document.getText()}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.reviewCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        await provider.sendMessage(`Review this code and provide feedback:\n\`\`\`${editor.document.languageId}\n${text || editor.document.getText()}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.suggestImprovements', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        await provider.sendMessage(`Suggest improvements for this code:\n\`\`\`${editor.document.languageId}\n${text || editor.document.getText()}\n\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.clearHistory', async () => {
        const confirm = await vscode.window.showWarningMessage('Are you sure you want to clear all chat history?', { modal: true }, 'Yes', 'No');
        if (confirm === 'Yes') {
            provider.clearHistory();
            vscode.window.showInformationMessage('Chat history cleared');
        }
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.openSettings', () => {
        vscode.commands.executeCommand('workbench.action.openSettings', '@ext:axion.axion-ai');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.exportConversation', async () => {
        const uri = await vscode.window.showSaveDialog({
            filters: {
                'Markdown': ['md'],
                'Text': ['txt'],
                'JSON': ['json']
            },
            defaultUri: vscode.Uri.file('axion-ai-conversation.md')
        });
        if (uri) {
            const exported = await provider.exportConversation();
            if (exported) {
                const fs = require('fs');
                fs.writeFileSync(uri.fsPath, exported);
                vscode.window.showInformationMessage('Conversation exported successfully');
            }
        }
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.importConversation', async () => {
        const uri = await vscode.window.showOpenDialog({
            filters: {
                'Markdown': ['md'],
                'Text': ['txt'],
                'JSON': ['json']
            },
            canSelectMany: false
        });
        if (uri && uri[0]) {
            const fs = require('fs');
            const content = fs.readFileSync(uri[0].fsPath, 'utf8');
            await provider.importConversation(content);
            vscode.window.showInformationMessage('Conversation imported successfully');
        }
    }));
    // Code Quality Analysis
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.analyzeCodeQuality', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        const code = text || editor.document.getText();
        const model = (0, AIModels_1.getModelById)('claude-sonnet-4') || (0, AIModels_1.getModelById)('gpt-4o') || null;
        if (model && aiService.hasApiKey(model.provider)) {
            vscode.window.showInformationMessage('Analyzing code quality...');
            const report = await codeQualityService.analyzeCode(model, code, editor.document.languageId, editor.document.uri.fsPath);
            const reportText = `Code Quality Analysis Report

Overall Score: ${report.overallScore}/100

Metrics:
- Maintainability: ${report.metrics.maintainability}/100
- Performance: ${report.metrics.performance}/100
- Security: ${report.metrics.security}/100
- Readability: ${report.metrics.readability}/100
- Testability: ${report.metrics.testability}/100

${report.issues.length > 0 ? `\nIssues Found (${report.issues.length}):\n${report.issues.map(i => `[${i.severity.toUpperCase()}] ${i.message}${i.suggestion ? ` - ${i.suggestion}` : ''}`).join('\n')}` : ''}

${report.suggestions.length > 0 ? `\nSuggestions:\n${report.suggestions.map(s => `- ${s}`).join('\n')}` : ''}

${report.strengths.length > 0 ? `\nStrengths:\n${report.strengths.map(s => `- ${s}`).join('\n')}` : ''}

Code analyzed:
\`\`\`${editor.document.languageId}
${code}
\`\`\``;
            await provider.sendMessage(reportText);
        }
        else {
            await provider.sendMessage(`Analyze code quality for:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
        }
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.checkSecurity', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        const code = text || editor.document.getText();
        const model = (0, AIModels_1.getModelById)('claude-sonnet-4') || (0, AIModels_1.getModelById)('gpt-4o') || null;
        if (model && aiService.hasApiKey(model.provider)) {
            vscode.window.showInformationMessage('Scanning for security vulnerabilities...');
            const issues = await codeQualityService.checkSecurity(model, code, editor.document.languageId);
            if (issues.length > 0) {
                const securityReport = `Security Analysis - Found ${issues.length} vulnerability/vulnerabilities:

${issues.map(i => `[${i.severity.toUpperCase()}] ${i.message}${i.suggestion ? `\nFix: ${i.suggestion}` : ''}`).join('\n\n')}

Code:
\`\`\`${editor.document.languageId}
${code}
\`\`\``;
                await provider.sendMessage(securityReport);
            }
            else {
                await provider.sendMessage(`Security scan complete. No obvious vulnerabilities found. Performing deep security analysis:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
            }
        }
        else {
            await provider.sendMessage(`Check for security vulnerabilities in:\n\`\`\`${editor.document.languageId}\n${code}\n\`\`\``);
        }
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.findPatterns', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const text = editor.document.getText();
        await provider.sendMessage(`Find and analyze code patterns, anti-patterns, and design patterns in this codebase:\n\`\`\`${editor.document.languageId}\n${text}\n\`\`\`

Look for:
- Design patterns (Singleton, Factory, Observer, etc.)
- Anti-patterns (God Object, Spaghetti Code, etc.)
- Code smells
- Repeated patterns
- Architectural patterns
- Best practices violations`);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.generateDocumentation', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        await provider.sendMessage(`Generate comprehensive documentation for this code including:
- Function/class descriptions
- Parameter documentation
- Return value documentation
- Usage examples
- Edge cases
- Performance notes
- Related code references

Code:
\`\`\`${editor.document.languageId}
${text || editor.document.getText()}
\`\`\``);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    context.subscriptions.push(vscode.commands.registerCommand('axion-ai.smartRefactor', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showWarningMessage('No active editor');
            return;
        }
        const selection = editor.selection;
        const text = editor.document.getText(selection.isEmpty ? undefined : selection);
        await provider.sendMessage(`Perform intelligent refactoring on this code. Analyze the code structure, identify refactoring opportunities, and apply best practices:

1. Extract methods/functions where appropriate
2. Remove code duplication
3. Improve naming and clarity
4. Simplify complex logic
5. Apply design patterns where beneficial
6. Improve error handling
7. Optimize performance
8. Enhance maintainability

Code to refactor:
\`\`\`${editor.document.languageId}
${text || editor.document.getText()}
\`\`\`

Provide the refactored code with explanations of all changes made.`);
        vscode.commands.executeCommand('axion-ai.chatView.focus');
    }));
    // Status bar item
    const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBarItem.text = '$(zap) Axion';
    statusBarItem.tooltip = 'Open Axion AI';
    statusBarItem.command = 'axion-ai.openPanel';
    statusBarItem.show();
    context.subscriptions.push(statusBarItem);
}
function deactivate() {
    console.log('Axion AI deactivated');
}
//# sourceMappingURL=extension.js.map