import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { CodeAnalyzer } from './analyzer.js';
import { promises as fs } from 'fs';
import path from 'path';
let codeAnalyzer;
let configManager;
export async function setupCodeIntelligenceTools(server, config) {
    configManager = config || new ConfigManager();
    codeAnalyzer = new CodeAnalyzer();
    // Add code intelligence tool handlers
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'analyze_code': {
                const { filePath } = args;
                const fullPath = path.isAbsolute(filePath)
                    ? filePath
                    : path.join(process.cwd(), filePath);
                try {
                    const analysis = await codeAnalyzer.analyzeFile(fullPath);
                    const suggestions = analysis.complexity.suggestions
                        .map(s => `• ${s.description} (${s.severity})`)
                        .join('\n');
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📊 Code Analysis: ${path.basename(filePath)}\n\n` +
                                    `📝 Language: ${analysis.language}\n` +
                                    `📏 Lines: ${analysis.metrics.lines} (${analysis.metrics.loc} LOC)\n` +
                                    `🔄 Complexity: ${analysis.complexity.cyclomatic}\n` +
                                    `📈 Maintainability: ${analysis.complexity.maintainabilityIndex.toFixed(1)}/100\n` +
                                    `📦 Dependencies: ${analysis.dependencies.length}\n` +
                                    `🔧 Functions: ${analysis.functions.length}\n` +
                                    `🏗️ Classes: ${analysis.classes.length}\n\n` +
                                    `💡 Suggestions:\n${suggestions || 'None - code looks good!'}`,
                            },
                        ],
                        structured: analysis,
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error analyzing file: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'analyze_project': {
                const { directory = '.', extensions = ['.ts', '.js', '.tsx', '.jsx'] } = args;
                const dir = path.isAbsolute(directory)
                    ? directory
                    : path.join(process.cwd(), directory);
                try {
                    const files = await findFiles(dir, extensions);
                    let totalComplexity = 0;
                    let totalLOC = 0;
                    let fileCount = 0;
                    const highComplexityFiles = [];
                    for (const file of files) {
                        try {
                            const analysis = await codeAnalyzer.analyzeFile(file);
                            totalComplexity += analysis.complexity.cyclomatic;
                            totalLOC += analysis.metrics.loc;
                            fileCount++;
                            if (analysis.complexity.cyclomatic > 10) {
                                highComplexityFiles.push(`${path.relative(dir, file)} (complexity: ${analysis.complexity.cyclomatic})`);
                            }
                        }
                        catch (error) {
                            // Skip files that can't be analyzed
                        }
                    }
                    const avgComplexity = fileCount > 0 ? totalComplexity / fileCount : 0;
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `📊 Project Analysis Summary\n\n` +
                                    `📁 Files analyzed: ${fileCount}\n` +
                                    `📏 Total LOC: ${totalLOC}\n` +
                                    `🔄 Average complexity: ${avgComplexity.toFixed(1)}\n` +
                                    `⚠️  High complexity files: ${highComplexityFiles.length}\n\n` +
                                    (highComplexityFiles.length > 0
                                        ? `Files needing attention:\n${highComplexityFiles.join('\n')}`
                                        : 'All files have reasonable complexity! 🎉'),
                            },
                        ],
                        structured: {
                            summary: {
                                filesAnalyzed: fileCount,
                                totalLOC,
                                totalComplexity,
                                averageComplexity: avgComplexity,
                                highComplexityCount: highComplexityFiles.length,
                            },
                            highComplexityFiles,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error analyzing project: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'suggest_refactoring': {
                const { filePath } = args;
                const fullPath = path.isAbsolute(filePath)
                    ? filePath
                    : path.join(process.cwd(), filePath);
                try {
                    const analysis = await codeAnalyzer.analyzeFile(fullPath);
                    const suggestions = [];
                    // Function-specific suggestions
                    for (const func of analysis.functions) {
                        if (func.length > 20) {
                            suggestions.push({
                                type: 'function',
                                target: func.name,
                                issue: 'Function too long',
                                suggestion: `Consider breaking ${func.name} into smaller functions`,
                                line: func.line,
                            });
                        }
                        if (func.params.length > 3) {
                            suggestions.push({
                                type: 'function',
                                target: func.name,
                                issue: 'Too many parameters',
                                suggestion: `Consider using an options object for ${func.name}`,
                                line: func.line,
                            });
                        }
                    }
                    // File-level suggestions
                    if (analysis.dependencies.length > 10) {
                        suggestions.push({
                            type: 'file',
                            issue: 'Too many dependencies',
                            suggestion: 'Consider splitting this module to reduce coupling',
                        });
                    }
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `🔧 Refactoring Suggestions for ${path.basename(filePath)}\n\n` +
                                    suggestions.map((s, i) => `${i + 1}. ${s.issue}${s.line ? ` (line ${s.line})` : ''}\n` +
                                        `   💡 ${s.suggestion}`).join('\n\n') ||
                                    '✅ No refactoring suggestions - code looks clean!',
                            },
                        ],
                        structured: {
                            file: filePath,
                            suggestions,
                            metrics: analysis.metrics,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Error analyzing file: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            default:
                // Not a code intelligence tool
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'analyze_code',
                description: 'Analyze code quality, complexity, and maintainability',
                inputSchema: {
                    type: 'object',
                    properties: {
                        filePath: { type: 'string', description: 'Path to the file to analyze' },
                    },
                    required: ['filePath'],
                },
                outputSchema: {
                    type: 'object',
                    properties: {
                        file: { type: 'string' },
                        language: { type: 'string' },
                        metrics: { type: 'object' },
                        complexity: { type: 'object' },
                        dependencies: { type: 'array', items: { type: 'string' } },
                        functions: { type: 'array', items: { type: 'object' } },
                        classes: { type: 'array', items: { type: 'object' } },
                    },
                },
            },
            {
                name: 'analyze_project',
                description: 'Analyze code quality across the entire project',
                inputSchema: {
                    type: 'object',
                    properties: {
                        directory: { type: 'string', default: '.', description: 'Project directory to analyze' },
                        extensions: {
                            type: 'array',
                            items: { type: 'string' },
                            default: ['.ts', '.js', '.tsx', '.jsx'],
                            description: 'File extensions to include'
                        },
                    },
                    required: [],
                },
            },
            {
                name: 'suggest_refactoring',
                description: 'Get specific refactoring suggestions for a file',
                inputSchema: {
                    type: 'object',
                    properties: {
                        filePath: { type: 'string', description: 'Path to the file to analyze' },
                    },
                    required: ['filePath'],
                },
            },
        ],
        resources: [],
    };
}
async function findFiles(dir, extensions) {
    const files = [];
    async function walk(currentDir) {
        const entries = await fs.readdir(currentDir, { withFileTypes: true });
        for (const entry of entries) {
            const fullPath = path.join(currentDir, entry.name);
            if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
                await walk(fullPath);
            }
            else if (entry.isFile() && extensions.some(ext => entry.name.endsWith(ext))) {
                files.push(fullPath);
            }
        }
    }
    await walk(dir);
    return files;
}
//# sourceMappingURL=index.js.map