// engine/github/review-analyzer.ts — Analyze PR diffs for review findings.
// Security patterns to detect in diffs
const SECURITY_PATTERNS = [
    {
        pattern: /eval\s*\(/,
        message: 'Use of eval() detected',
        suggestion: 'Avoid eval(); use safer alternatives like JSON.parse()',
    },
    {
        pattern: /innerHTML\s*=/,
        message: 'Direct innerHTML assignment',
        suggestion: 'Use textContent or a sanitization library',
    },
    {
        pattern: /password\s*[:=]\s*['"][^'"]+['"]/,
        message: 'Hardcoded password detected',
        suggestion: 'Use environment variables for secrets',
    },
    {
        pattern: /(?:api[_-]?key|secret|token)\s*[:=]\s*['"][^'"]+['"]/,
        message: 'Hardcoded secret/token detected',
        suggestion: 'Use environment variables for secrets',
    },
    {
        pattern: /disable.*ssl|verify\s*=\s*false/i,
        message: 'SSL verification disabled',
        suggestion: 'Enable SSL verification in production',
    },
    {
        pattern: /exec\s*\(.*\$/,
        message: 'Shell command with variable interpolation',
        suggestion: 'Sanitize inputs before shell execution',
    },
];
// Performance patterns to detect in diffs
const PERFORMANCE_PATTERNS = [
    {
        pattern: /\.forEach\s*\(.*\.forEach/,
        message: 'Nested forEach detected (O(n^2))',
        suggestion: 'Consider using a Map or Set for lookups',
    },
    {
        pattern: /JSON\.parse\(JSON\.stringify/,
        message: 'Deep clone via JSON roundtrip',
        suggestion: 'Use structuredClone() or a dedicated deep-clone utility',
    },
    {
        pattern: /new RegExp\(/,
        message: 'RegExp created in a loop or hot path',
        suggestion: 'Pre-compile RegExp outside the loop',
    },
];
/**
 * Parse a unified diff to extract file-level stats.
 */
export function parseDiffStats(diff) {
    const files = [];
    let additions = 0;
    let deletions = 0;
    for (const line of diff.split('\n')) {
        if (line.startsWith('diff --git')) {
            const match = /b\/(.+)$/.exec(line);
            if (match?.[1]) {
                files.push(match[1]);
            }
        }
        else if (line.startsWith('+') && !line.startsWith('+++')) {
            additions++;
        }
        else if (line.startsWith('-') && !line.startsWith('---')) {
            deletions++;
        }
    }
    return { filesChanged: files.length, additions, deletions, files };
}
/**
 * Analyze a diff for review findings based on review type.
 */
export function analyzeDiff(diff, reviewType) {
    const findings = [];
    const lines = diff.split('\n');
    let currentFile = '';
    let lineNumber = 0;
    for (const line of lines) {
        if (line.startsWith('diff --git')) {
            const match = /b\/(.+)$/.exec(line);
            currentFile = match?.[1] ?? '';
            lineNumber = 0;
            continue;
        }
        const hunkMatch = /^@@\s+-\d+(?:,\d+)?\s+\+(\d+)/.exec(line);
        if (hunkMatch?.[1]) {
            lineNumber = Number(hunkMatch[1]);
            continue;
        }
        if (line.startsWith('+') && !line.startsWith('+++')) {
            const patterns = getPatterns(reviewType);
            for (const { pattern, message, suggestion } of patterns) {
                if (pattern.test(line)) {
                    findings.push({
                        file: currentFile,
                        line: lineNumber,
                        severity: reviewType === 'security' ? 'critical' : 'warning',
                        category: reviewType,
                        message,
                        suggestion,
                    });
                }
            }
            lineNumber++;
        }
        else if (!line.startsWith('-')) {
            lineNumber++;
        }
    }
    return findings;
}
function getPatterns(reviewType) {
    switch (reviewType) {
        case 'security':
            return SECURITY_PATTERNS;
        case 'performance':
            return PERFORMANCE_PATTERNS;
        case 'detailed':
            return [...SECURITY_PATTERNS, ...PERFORMANCE_PATTERNS];
        case 'summary':
        case 'quality':
        default:
            return [];
    }
}
/**
 * Generate a summary finding for the overall diff.
 */
export function generateSummaryFinding(filesChanged, additions, deletions) {
    const complexity = additions + deletions > 500 ? 'warning' : 'info';
    return {
        file: '(overall)',
        severity: complexity,
        category: 'summary',
        message: `${String(filesChanged)} files changed, +${String(additions)} -${String(deletions)} lines`,
        suggestion: additions + deletions > 500
            ? 'Consider splitting this PR into smaller, focused changes'
            : 'PR size looks manageable',
    };
}
//# sourceMappingURL=review-analyzer.js.map