"use strict";
/**
 * Production-grade Error Aggregator
 * Implements AGENTS.md principles:
 * - "Collect ALL errors before reporting"
 * - "Fail fast, fail clearly"
 * - "Report errors clearly with context"
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetGlobalErrorAggregator = exports.getGlobalErrorAggregator = exports.CompilationErrorAggregator = void 0;
class CompilationErrorAggregator {
    constructor() {
        this.errors = [];
        this.warnings = [];
        this.criticalErrors = [];
        this.maxErrors = 100; // Prevent memory explosion
        this.failFastOnCritical = true;
    }
    /**
     * Collect an error or warning with automatic categorization
     * Does NOT fail immediately - aggregates for later reporting
     * EXCEPT for critical errors when failFastOnCritical is enabled
     */
    collect(error) {
        // Add timestamp if not present
        if (!error.timestamp) {
            error.timestamp = Date.now();
        }
        // Auto-categorize if not set
        if (error.category === 'unknown') {
            error.category = this.categorizeError(error);
        }
        if (error.severity === 'critical') {
            this.criticalErrors.push(error);
            // Fail fast on critical errors
            if (this.failFastOnCritical) {
                this.reportAll();
                this.failFast();
            }
        }
        else if (error.severity === 'warning') {
            this.warnings.push(error);
        }
        else if (this.errors.length < this.maxErrors) {
            this.errors.push(error);
        }
    }
    /**
     * Automatically categorize error based on message and code
     */
    categorizeError(error) {
        const message = error.message.toLowerCase();
        const code = error.code.toLowerCase();
        if (code.includes('syntax') || message.includes('syntax'))
            return 'syntax';
        if (code.includes('type') || message.includes('type'))
            return 'type';
        if (code.includes('resolution') || code.includes('module') || message.includes('not found'))
            return 'resolution';
        if (code.includes('permission') || code.includes('eacces'))
            return 'system';
        if (code.includes('validation') || message.includes('invalid'))
            return 'validation';
        if (code.includes('runtime'))
            return 'runtime';
        return 'unknown';
    }
    /**
     * Check if compilation should stop
     */
    shouldStop() {
        return this.errors.length >= this.maxErrors;
    }
    /**
     * Report header and summary statistics
     */
    reportHeaderAndSummary(totalIssues) {
        console.error('\n╔═══════════════════════════════════════════════════════════════╗');
        console.error('║            COMPILATION ERROR REPORT                           ║');
        console.error('╚═══════════════════════════════════════════════════════════════╝\n');
        console.error(`📊 Summary:`);
        console.error(`   Total issues: ${totalIssues}`);
        console.error(`   Critical: ${this.criticalErrors.length}, Errors: ${this.errors.length}, Warnings: ${this.warnings.length}`);
        const byCategory = this.getErrorsByCategory();
        if (byCategory.size > 0) {
            console.error(`   By category: ${Array.from(byCategory.entries())
                .map(([cat, count]) => `${cat}=${count}`)
                .join(', ')}`);
        }
        console.error('');
    }
    /**
     * Report critical errors section
     */
    reportCriticalErrors() {
        if (this.criticalErrors.length === 0) {
            return;
        }
        console.error('🚨 CRITICAL ERRORS (System will exit):');
        const criticalByFile = this.groupByFile(this.criticalErrors);
        for (const [file, fileErrors] of criticalByFile.entries()) {
            console.error(`\n📄 ${file}:`);
            for (const error of fileErrors) {
                this.reportSingleError(error, '🚨');
            }
        }
        console.error('');
    }
    /**
     * Report errors section
     */
    reportErrors() {
        if (this.errors.length === 0) {
            return;
        }
        console.error(`❌ ERRORS (${this.errors.length}):`);
        const errorsByFile = this.groupByFile(this.errors);
        for (const [file, fileErrors] of errorsByFile.entries()) {
            console.error(`\n📄 ${file}:`);
            for (const error of fileErrors) {
                this.reportSingleError(error, '❌');
            }
        }
        if (this.errors.length >= this.maxErrors) {
            console.error(`\n⚠️  Error limit reached. There may be more errors.`);
        }
        console.error('');
    }
    /**
     * Report warnings section
     */
    reportWarnings() {
        if (this.warnings.length === 0) {
            return;
        }
        console.error(`⚠️  WARNINGS (${this.warnings.length}):`);
        const warningsByFile = this.groupByFile(this.warnings);
        for (const [file, fileWarnings] of warningsByFile.entries()) {
            console.error(`\n📄 ${file}:`);
            for (const warning of fileWarnings) {
                this.reportSingleError(warning, '⚠️ ');
            }
        }
        console.error('');
    }
    /**
     * Report all collected errors and warnings
     * Provides comprehensive context for debugging
     */
    reportAll() {
        const totalIssues = this.criticalErrors.length + this.errors.length + this.warnings.length;
        if (totalIssues === 0) {
            return;
        }
        this.reportHeaderAndSummary(totalIssues);
        this.reportCriticalErrors();
        this.reportErrors();
        this.reportWarnings();
        console.error('╔═══════════════════════════════════════════════════════════════╗');
        console.error('║            END OF ERROR REPORT                                ║');
        console.error('╚═══════════════════════════════════════════════════════════════╝\n');
    }
    /**
     * Report a single error with formatting
     */
    reportSingleError(error, icon) {
        let location = '';
        if (error.line) {
            location = `:${error.line}`;
            if (error.column) {
                location += `:${error.column}`;
            }
        }
        const locationPrefix = location ? ` Line ${location}` : '';
        console.error(`  ${icon} [${error.code}]${locationPrefix}`);
        console.error(`     ${error.message}`);
        if (error.category !== 'unknown') {
            console.error(`     Category: ${error.category}`);
        }
        if (error.suggestion) {
            console.error(`     💡 Suggestion: ${error.suggestion}`);
        }
        if (error.stack && process.env.DEBUG) {
            console.error(`     Stack: ${error.stack.split('\n')[0]}`);
        }
    }
    /**
     * Get errors grouped by category
     */
    getErrorsByCategory() {
        const byCategory = new Map();
        const allErrors = [...this.criticalErrors, ...this.errors, ...this.warnings];
        for (const error of allErrors) {
            const count = byCategory.get(error.category) || 0;
            byCategory.set(error.category, count + 1);
        }
        return byCategory;
    }
    /**
     * Fail fast with comprehensive error reporting
     * Implements proper exit codes based on error severity
     */
    failFast() {
        this.reportAll();
        if (this.criticalErrors.length > 0) {
            console.error(`💥 Exiting due to ${this.criticalErrors.length} critical error(s). System cannot continue.\n`);
            process.exit(2); // Critical failure
        }
        if (this.errors.length > 0) {
            console.error(`❌ Compilation failed with ${this.errors.length} error(s). Please fix and retry.\n`);
            process.exit(1); // Standard failure
        }
        // No errors - should not be called
        throw new Error('failFast called without errors');
    }
    /**
     * Get error count
     */
    getErrorCount() {
        return this.errors.length;
    }
    /**
     * Get critical error count
     */
    getCriticalErrorCount() {
        return this.criticalErrors.length;
    }
    /**
     * Get warning count
     */
    getWarningCount() {
        return this.warnings.length;
    }
    /**
     * Get total issue count
     */
    getTotalCount() {
        return this.criticalErrors.length + this.errors.length + this.warnings.length;
    }
    /**
     * Check if there are any errors
     */
    hasErrors() {
        return this.errors.length > 0 || this.criticalErrors.length > 0;
    }
    /**
     * Check if there are any critical errors
     */
    hasCriticalErrors() {
        return this.criticalErrors.length > 0;
    }
    /**
     * Clear all collected errors and warnings
     */
    clear() {
        this.errors = [];
        this.warnings = [];
        this.criticalErrors = [];
    }
    /**
     * Set whether to fail fast on critical errors
     */
    setFailFastOnCritical(enabled) {
        this.failFastOnCritical = enabled;
    }
    /**
     * Get all errors (critical, errors, warnings)
     */
    getAllErrors() {
        return [...this.criticalErrors, ...this.errors, ...this.warnings];
    }
    groupByFile(items) {
        const grouped = new Map();
        for (const item of items) {
            const file = item.file || 'unknown';
            if (!grouped.has(file)) {
                grouped.set(file, []);
            }
            grouped.get(file).push(item);
        }
        // Sort by line number within each file
        for (const fileErrors of grouped.values()) {
            fileErrors.sort((a, b) => (a.line || 0) - (b.line || 0));
        }
        return grouped;
    }
    /**
     * Get common error suggestions
     */
    static getSuggestion(code) {
        const suggestions = {
            CIRCULAR_DEP: 'Refactor to remove circular dependency or use dynamic imports',
            UNDEFINED_VAR: 'Check variable name spelling or ensure it is declared',
            TYPE_MISMATCH: 'Ensure types match or add explicit type conversion',
            MISSING_MODULE: 'Run npm install or check the module path',
            SYNTAX_ERROR: 'Check for missing semicolons, brackets, or quotes',
            PERMISSION_DENIED: 'Check file permissions or run with appropriate privileges',
            EACCES: 'Permission denied - check file/directory permissions',
            ENOENT: 'File or directory not found - verify the path exists',
            NODE_VERSION: 'Upgrade Node.js to a supported version (20.x, 22.x, 23.x, 24.x)',
            VALIDATION_ERROR: 'Fix validation errors before running in production mode',
        };
        return suggestions[code];
    }
    /**
     * Create error from exception with auto-categorization
     */
    static fromException(error, file, code = 'UNKNOWN_ERROR') {
        const message = error.message;
        let category = 'unknown';
        let severity = 'error';
        // Auto-detect category from error message
        if (message.includes('EACCES') || message.includes('ENOENT')) {
            category = 'system';
            severity = 'critical';
        }
        else if (message.includes('syntax')) {
            category = 'syntax';
        }
        else if (message.includes('type')) {
            category = 'type';
        }
        else if (message.includes('not found') || message.includes('cannot find')) {
            category = 'resolution';
        }
        else if (message.includes('validation')) {
            category = 'validation';
            severity = 'critical';
        }
        return {
            file,
            code,
            message,
            severity,
            category,
            suggestion: this.getSuggestion(code),
            timestamp: Date.now(),
            stack: error.stack,
        };
    }
}
exports.CompilationErrorAggregator = CompilationErrorAggregator;
/**
 * Global error aggregator for CLI usage
 */
let globalAggregator = null;
/**
 * Get or create global error aggregator
 */
function getGlobalErrorAggregator() {
    globalAggregator ?? (globalAggregator = new CompilationErrorAggregator());
    return globalAggregator;
}
exports.getGlobalErrorAggregator = getGlobalErrorAggregator;
/**
 * Reset global error aggregator
 */
function resetGlobalErrorAggregator() {
    globalAggregator = null;
}
exports.resetGlobalErrorAggregator = resetGlobalErrorAggregator;
//# sourceMappingURL=error-aggregator.js.map