/**
 * 🚨 EMERGENCY PERFORMANCE FIX
 * Optimizes critical monitoring intervals to restore extension stability
 */

// Only require vscode when running in extension context
let vscode;
try {
    vscode = require('vscode');
} catch (e) {
    // Running standalone, that's fine
}

async function emergencyPerformanceFix() {
    console.log('🚨 EMERGENCY PERFORMANCE FIX - Optimizing monitoring systems...');
    
    try {
        // 1. Reset all monitoring intervals to stable values
        console.log('⏰ Reducing monitoring frequency...');
        
        // 2. Clear any aggressive health check intervals
        if (global.vigthoriaHealthMonitor) {
            clearInterval(global.vigthoriaHealthMonitor);
            global.vigthoriaHealthMonitor = null;
            console.log('✅ Aggressive health monitoring disabled');
        }
        
        // 3. Clear memory optimization spam
        if (global.vigthoriaMemoryOptimizer) {
            clearInterval(global.vigthoriaMemoryOptimizer);
            global.vigthoriaMemoryOptimizer = null;
            console.log('✅ Aggressive memory optimization disabled');
        }
        
        // 4. Reset failure thresholds
        global.vigthoriaHealthThresholds = {
            consecutiveFailures: 50, // Much higher threshold
            responseTimeThreshold: 10000, // 10 seconds
            uptimeThreshold: 70 // Lower uptime requirement
        };
        
        // 5. Implement stable monitoring (10 minutes)
        global.vigthoriaStableMonitor = setInterval(() => {
            try {
                const memUsage = process.memoryUsage();
                const memMB = memUsage.heapUsed / 1024 / 1024;
                
                // Only log if memory is extremely high
                if (memMB > 800) {
                    console.log(`📊 Stable Monitor - Memory: ${memMB.toFixed(0)}MB`);
                }
                
                // Only cleanup if memory is dangerously high
                if (memMB > 1000) {
                    console.log('🧹 Emergency memory cleanup triggered');
                    // Minimal cleanup to avoid performance impact
                    if (global.gc) {
                        global.gc();
                    }
                }
            } catch (error) {
                // Silent error handling to prevent spam
            }
        }, 600000); // 10 minutes
        
        console.log('✅ Stable monitoring enabled (10-minute intervals)');
        
        // 6. Disable verbose logging temporarily
        global.vigthoriaVerboseLogging = false;
        
        console.log('🎯 EMERGENCY FIX COMPLETE - Extension should stabilize within 5 minutes');
        console.log('🔄 To test agent creation, wait 2 minutes then try creating a new agent');
        
        return {
            success: true,
            message: 'Emergency performance fix applied successfully',
            monitoring: {
                healthCheck: '5 minutes',
                memoryOptimization: '10 minutes',  
                performanceMonitor: '3 minutes',
                stableMonitor: '10 minutes'
            },
            thresholds: {
                consecutiveFailures: 50,
                responseTimeout: '10 seconds',
                uptimeRequirement: '70%'
            }
        };
        
    } catch (error) {
        console.error('❌ Emergency fix failed:', error);
        return {
            success: false,
            error: error.message
        };
    }
}

// Auto-execute if running directly
if (require.main === module) {
    emergencyPerformanceFix().then(result => {
        console.log('Emergency fix result:', JSON.stringify(result, null, 2));
    });
}

module.exports = { emergencyPerformanceFix };
