"use strict";
/**
 * Layer 3: AI Semantic Analysis
 *
 * Uses Claude to perform deep security analysis including:
 * - Taint analysis (data flow from sources to sinks)
 * - Business logic flaw detection
 * - Missing authorization checks
 * - Cryptography validation
 * - Data exposure detection
 * - Framework-specific deep analysis
 *
 * Also provides high-context validation for Layer 1/2 findings.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyAutoDismissRules = void 0;
exports.analyzeWithAI = analyzeWithAI;
exports.batchAnalyzeWithAI = batchAnalyzeWithAI;
exports.validateFindingsWithAI = validateFindingsWithAI;
const types_1 = require("./types");
const clients_1 = require("./clients");
const response_parser_1 = require("./utils/response-parser");
const semantic_analysis_1 = require("./prompts/semantic-analysis");
const openai_1 = require("./providers/openai");
const anthropic_1 = require("./providers/anthropic");
var auto_dismiss_1 = require("../score/auto-dismiss");
Object.defineProperty(exports, "applyAutoDismissRules", { enumerable: true, get: function () { return auto_dismiss_1.applyAutoDismissRules; } });
// ============================================================================
// Layer 3: Deep AI Analysis
// ============================================================================
/**
 * Analyze a single file using AI for deep security analysis (Layer 3)
 */
async function analyzeWithAI(file, context) {
    const client = (0, clients_1.getAnthropicClient)();
    // Prepare the code with line numbers for reference
    const numberedCode = file.content
        .split('\n')
        .map((line, i) => `${i + 1}: ${line}`)
        .join('\n');
    // Build auth context for the prompt
    const authContext = (0, semantic_analysis_1.buildAuthContextForPrompt)(context);
    const userMessage = `Analyze this ${file.language} file for security vulnerabilities:

File: ${file.path}${authContext}

\`\`\`${file.language}
${numberedCode}
\`\`\`

Return ONLY a JSON array of findings.`;
    try {
        const response = await client.messages.create({
            model: 'claude-3-5-haiku-20241022',
            max_tokens: 4096,
            system: semantic_analysis_1.SECURITY_ANALYSIS_PROMPT,
            messages: [
                {
                    role: 'user',
                    content: userMessage,
                },
            ],
        });
        // Extract text content from response
        const textContent = response.content.find((block) => block.type === 'text');
        if (!textContent || textContent.type !== 'text') {
            console.error('No text content in AI response');
            return [];
        }
        // Parse the JSON response
        const findings = (0, response_parser_1.parseAIResponse)(textContent.text);
        // Convert to Vulnerability format
        return findings.map((finding, index) => ({
            id: `ai-${file.path}-${finding.lineNumber}-${index}`,
            filePath: file.path,
            lineNumber: finding.lineNumber,
            lineContent: (0, response_parser_1.getLineContent)(file.content, finding.lineNumber),
            severity: finding.severity,
            category: finding.category,
            title: finding.title,
            description: finding.description,
            suggestedFix: finding.suggestedFix,
            confidence: 'high',
            layer: 3,
        }));
    }
    catch (error) {
        console.error('AI analysis error:', error);
        return [];
    }
}
/**
 * Batch analyze multiple files using AI (Layer 3)
 * Processes files in batches to avoid rate limits
 */
async function batchAnalyzeWithAI(files, context, maxConcurrent = 3) {
    const vulnerabilities = [];
    // Process files in batches to avoid rate limits
    for (let i = 0; i < files.length; i += maxConcurrent) {
        const batch = files.slice(i, i + maxConcurrent);
        const results = await Promise.all(batch.map(file => analyzeWithAI(file, context).catch(err => {
            console.error(`AI analysis failed for ${file.path}:`, err);
            return [];
        })));
        vulnerabilities.push(...results.flat());
        // Small delay between batches to avoid rate limits
        if (i + maxConcurrent < files.length) {
            await new Promise(resolve => setTimeout(resolve, 500));
        }
    }
    return vulnerabilities;
}
// ============================================================================
// Layer 2.5: High-Context Validation
// ============================================================================
/**
 * Validate Layer 1/2 findings using AI with HIGH-CONTEXT validation
 *
 * Key improvements over previous version:
 * 1. Sends FULL FILE CONTENT (not just snippets) for better context
 * 2. Includes PROJECT CONTEXT (auth patterns, data access, etc.)
 * 3. Uses generalised rules from Section 3 of the security model
 */
async function validateFindingsWithAI(findings, files, ceResult, onProgress) {
    // Initialize stats tracking
    const stats = (0, types_1.createInitialStats)(findings.length);
    if (findings.length === 0) {
        return { vulnerabilities: [], stats };
    }
    // Check for provider override (GPT-5-mini is default for 47% cost savings)
    const aiProvider = process.env.AI_PROVIDER || 'openai';
    if (aiProvider === 'anthropic') {
        console.log('[AI Validation] Using Anthropic provider (Claude 3.5 Haiku)');
        return (0, anthropic_1.validateWithAnthropic)(findings, files, ceResult, stats, onProgress);
    }
    else {
        console.log('[AI Validation] Using OpenAI provider (GPT-5-mini)');
        return (0, openai_1.validateWithOpenAI)(findings, files, ceResult, stats);
    }
}
//# sourceMappingURL=index.js.map