"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeQualityService = void 0;
class CodeQualityService {
    aiService;
    fileManager;
    constructor(aiService, fileManager) {
        this.aiService = aiService;
        this.fileManager = fileManager;
    }
    async analyzeCode(model, code, language, filePath) {
        const context = filePath ? await this.getFileContext(filePath) : '';
        const messages = [
            {
                role: 'system',
                content: `You are an expert code quality analyzer. Analyze the provided code and generate a comprehensive quality report.

Your analysis should include:
1. Overall quality score (0-100)
2. Detailed metrics for: maintainability, performance, security, readability, testability
3. Specific issues found with severity levels
4. Actionable suggestions for improvement
5. Strengths of the code

Format your response as JSON with this structure:
{
  "overallScore": 85,
  "metrics": {
    "maintainability": 80,
    "performance": 90,
    "security": 75,
    "readability": 85,
    "testability": 70
  },
  "issues": [
    {
      "type": "warning",
      "severity": "medium",
      "message": "Missing error handling",
      "line": 15,
      "category": "best-practice",
      "suggestion": "Add try-catch block"
    }
  ],
  "suggestions": ["Add type annotations", "Extract magic numbers to constants"],
  "strengths": ["Clear naming", "Good structure"]
}`
            },
            {
                role: 'user',
                content: `Analyze this ${language} code:

\`\`\`${language}
${code}
\`\`\`

${context ? `\nContext:\n${context}` : ''}

Provide a comprehensive code quality analysis.`
            }
        ];
        try {
            const response = await this.aiService.chat(model, messages, 'ask', '');
            return this.parseQualityReport(response.content);
        }
        catch (error) {
            console.error('Error analyzing code quality:', error);
            return this.getDefaultReport();
        }
    }
    async detectBugs(model, code, language) {
        const messages = [
            {
                role: 'system',
                content: `You are an expert bug detector. Analyze code for potential bugs, errors, and issues.

Look for:
- Logic errors
- Null pointer exceptions
- Race conditions
- Memory leaks
- Type errors
- Off-by-one errors
- Infinite loops
- Resource leaks
- Security vulnerabilities
- Edge cases not handled

Format as JSON array of issues.`
            },
            {
                role: 'user',
                content: `Find bugs in this ${language} code:

\`\`\`${language}
${code}
\`\`\``
            }
        ];
        try {
            const response = await this.aiService.chat(model, messages, 'ask', '');
            return this.parseIssues(response.content);
        }
        catch (error) {
            console.error('Error detecting bugs:', error);
            return [];
        }
    }
    async suggestOptimizations(model, code, language) {
        const messages = [
            {
                role: 'system',
                content: `You are a performance optimization expert. Analyze code and suggest optimizations for:
- Algorithm efficiency
- Memory usage
- CPU usage
- Database queries
- Network calls
- Caching opportunities
- Parallelization
- Resource management

Provide specific, actionable optimization suggestions.`
            },
            {
                role: 'user',
                content: `Suggest optimizations for this ${language} code:

\`\`\`${language}
${code}
\`\`\``
            }
        ];
        try {
            const response = await this.aiService.chat(model, messages, 'ask', '');
            return this.parseSuggestions(response.content);
        }
        catch (error) {
            console.error('Error suggesting optimizations:', error);
            return [];
        }
    }
    async checkSecurity(model, code, language) {
        const messages = [
            {
                role: 'system',
                content: `You are a security expert. Analyze code for security vulnerabilities:

- SQL injection
- XSS vulnerabilities
- CSRF issues
- Authentication/authorization flaws
- Sensitive data exposure
- Insecure dependencies
- Hardcoded secrets
- Input validation issues
- Cryptographic weaknesses
- Access control problems

Format as JSON array of security issues.`
            },
            {
                role: 'user',
                content: `Check for security vulnerabilities in this ${language} code:

\`\`\`${language}
${code}
\`\`\``
            }
        ];
        try {
            const response = await this.aiService.chat(model, messages, 'ask', '');
            return this.parseIssues(response.content).filter(i => i.category === 'security');
        }
        catch (error) {
            console.error('Error checking security:', error);
            return [];
        }
    }
    async getFileContext(filePath) {
        try {
            const relatedFiles = await this.findRelatedFiles(filePath);
            let context = `File: ${filePath}\n`;
            for (const file of relatedFiles.slice(0, 3)) {
                const content = await this.fileManager.readFile(file);
                if (content) {
                    context += `\nRelated file ${file}:\n${content.content.substring(0, 500)}...\n`;
                }
            }
            return context;
        }
        catch {
            return '';
        }
    }
    async findRelatedFiles(filePath) {
        const allFiles = await this.fileManager.getWorkspaceFiles();
        const currentDir = filePath.substring(0, filePath.lastIndexOf('/') || filePath.lastIndexOf('\\'));
        return allFiles
            .filter(f => !f.isDirectory && f.path !== filePath)
            .filter(f => {
            const fileDir = f.path.substring(0, f.path.lastIndexOf('/') || f.path.lastIndexOf('\\'));
            return fileDir === currentDir || f.language === this.getLanguageFromPath(filePath);
        })
            .slice(0, 5)
            .map(f => f.path);
    }
    getLanguageFromPath(path) {
        const ext = path.substring(path.lastIndexOf('.'));
        const map = {
            '.ts': 'typescript',
            '.js': 'javascript',
            '.py': 'python',
            '.java': 'java'
        };
        return map[ext] || 'unknown';
    }
    parseQualityReport(content) {
        try {
            const jsonMatch = content.match(/\{[\s\S]*\}/);
            if (jsonMatch) {
                return JSON.parse(jsonMatch[0]);
            }
        }
        catch (error) {
            console.error('Error parsing quality report:', error);
        }
        return this.getDefaultReport();
    }
    parseIssues(content) {
        try {
            const jsonMatch = content.match(/\[[\s\S]*\]/);
            if (jsonMatch) {
                return JSON.parse(jsonMatch[0]);
            }
        }
        catch (error) {
            console.error('Error parsing issues:', error);
        }
        return [];
    }
    parseSuggestions(content) {
        const suggestions = [];
        const lines = content.split('\n');
        for (const line of lines) {
            if (line.trim().match(/^[-*•]\s+/) || line.trim().match(/^\d+\.\s+/)) {
                suggestions.push(line.trim().replace(/^[-*•]\s+/, '').replace(/^\d+\.\s+/, ''));
            }
        }
        return suggestions.length > 0 ? suggestions : ['No specific optimizations found'];
    }
    getDefaultReport() {
        return {
            overallScore: 0,
            metrics: {
                maintainability: 0,
                performance: 0,
                security: 0,
                readability: 0,
                testability: 0
            },
            issues: [],
            suggestions: [],
            strengths: []
        };
    }
}
exports.CodeQualityService = CodeQualityService;
//# sourceMappingURL=CodeQualityService.js.map