/**
 * 🔧 INTEGRATION EXAMPLE FOR MAIN EXTENSION.JS
 * This file shows how to integrate the Phase 1 optimization systems into the existing extension.js
 * 
 * INSTRUCTIONS:
 * 1. Add this code to the beginning of your main extension.js file
 * 2. Call initializePhase1Optimizations() in your activate() function
 * 3. The Phase 1 systems will automatically enhance your existing functionality
 */

// Add these imports at the top of extension.js
const { Phase1OptimizationManager } = require('./phase1-optimization-manager');

// Add this variable at the top level
let phase1Manager = null;

/**
 * Initialize Phase 1 optimization systems
 * Call this in your activate() function
 */
async function initializePhase1Optimizations(context, vscode) {
    try {
        console.log('🚀 Initializing Vigthoria Phase 1 optimizations...');
        
        // Create Phase 1 manager
        phase1Manager = new Phase1OptimizationManager(vscode);
        
        // Initialize all Phase 1 systems
        await phase1Manager.initialize();
        
        // Integrate with VS Code extension
        phase1Manager.integrateWithExtension(context);
        
        // Setup Phase 1 event handlers
        setupPhase1EventHandlers(vscode);
        
        console.log('✅ Phase 1 optimizations successfully initialized');
        
        // Show completion notification (only if vscode API is available)
        if (vscode && vscode.window && vscode.window.showInformationMessage) {
            vscode.window.showInformationMessage(
                '🎉 Vigthoria Phase 1 optimizations are now active!',
                'View Status'
            ).then(selection => {
                if (selection === 'View Status') {
                    vscode.commands.executeCommand('vigthoria.phase1.status');
                }
            });
        }
        
    } catch (error) {
        console.error('❌ Failed to initialize Phase 1 optimizations:', error);
        
        // Only show error message if vscode is available
        try {
            const vscodeModule = require('vscode');
            vscodeModule.window.showErrorMessage(`Phase 1 initialization failed: ${error.message}`);
        } catch (vscodeError) {
            console.log('⚠️ Could not show error notification - VSCode API not available');
        }
    }
}

/**
 * Setup event handlers for Phase 1 systems
 */
function setupPhase1EventHandlers(vscode) {
    if (!phase1Manager) return;
    
    // Listen for optimization progress
    phase1Manager.on('optimizationProgress', (data) => {
        console.log(`📊 Phase ${data.phase} Progress: ${data.progress}%`);
    });
    
    // Listen for system errors
    phase1Manager.on('systemError', (data) => {
        console.error(`🚨 System error in ${data.system}:`, data.error);
        try {
            const vscode = require('vscode');
            if (vscode && vscode.window) {
                vscode.window.showWarningMessage(`System warning: ${data.error}`);
            }
        } catch (err) {
            // VS Code API not available, just log
            console.warn('VS Code API not available for error notification');
        }
    });
    
    // Listen for health report generation
    phase1Manager.on('healthReportGenerated', (report) => {
        console.log('📊 System health report generated:', report.overallHealth);
    });
}

/**
 * Enhanced command execution with Phase 1 integration
 * Use this wrapper for your existing commands to get automatic error handling and queuing
 */
async function executeCommandWithPhase1(commandName, handler, ...args) {
    if (!phase1Manager) {
        // Fallback to direct execution if Phase 1 not initialized
        return await handler(...args);
    }
    
    try {
        // Get request queue system
        const requestQueue = phase1Manager.systems.get('requestQueue');
        
        if (requestQueue) {
            // Queue the command execution for optimal performance
            return await requestQueue.enqueueRequest('ai_requests', {
                action: 'execute_command',
                data: { commandName, args }
            }, {
                priority: 1,
                timeout: 30000
            });
        } else {
            // Direct execution with error boundary
            const errorBoundary = phase1Manager.systems.get('errorBoundary');
            if (errorBoundary) {
                return await errorBoundary.executeWithBoundary(
                    () => handler(...args),
                    { context: `command_${commandName}` }
                );
            }
        }
        
        // Fallback to direct execution
        return await handler(...args);
        
    } catch (error) {
        console.error(`❌ Command ${commandName} failed:`, error);
        // Use global vscode if available, or the one passed in during initialization
        const vscode = require('vscode');
        if (vscode && vscode.window) {
            vscode.window.showErrorMessage(`Command failed: ${error.message}`);
        }
        throw error;
    }
}

/**
 * Enhanced AI request processing with Phase 1 integration
 * Use this for your AI model calls to get automatic queuing and error handling
 */
async function processAIRequestWithPhase1(provider, model, prompt, options = {}) {
    if (!phase1Manager) {
        // Fallback to your existing AI processing
        return await processAIRequestDirect(provider, model, prompt, options);
    }
    
    try {
        const requestQueue = phase1Manager.systems.get('requestQueue');
        
        if (requestQueue) {
            return await requestQueue.enqueueRequest('ai_requests', {
                action: 'chat',
                data: { provider, model, prompt, options }
            }, {
                priority: options.priority || 1,
                timeout: options.timeout || 60000,
                userId: options.userId || 'anonymous'
            });
        }
        
        // Fallback to direct processing
        return await processAIRequestDirect(provider, model, prompt, options);
        
    } catch (error) {
        console.error('❌ AI request failed:', error);
        
        // The error boundary will handle this automatically
        throw error;
    }
}

/**
 * Enhanced file operations with Phase 1 integration
 */
async function performFileOperationWithPhase1(operation, path, content = null) {
    if (!phase1Manager) {
        return await performFileOperationDirect(operation, path, content);
    }
    
    try {
        const requestQueue = phase1Manager.systems.get('requestQueue');
        
        if (requestQueue) {
            return await requestQueue.enqueueRequest('file_operations', {
                operation: operation,
                path: path,
                content: content
            }, {
                priority: 2,
                timeout: 15000
            });
        }
        
        return await performFileOperationDirect(operation, path, content);
        
    } catch (error) {
        console.error(`❌ File operation ${operation} failed:`, error);
        throw error;
    }
}

/**
 * Get Phase 1 system status for debugging
 */
function getPhase1Status() {
    if (!phase1Manager) {
        return { status: 'not_initialized' };
    }
    
    return phase1Manager.getSystemStatus();
}

/**
 * Get Phase 1 optimization metrics
 */
function getPhase1Metrics() {
    if (!phase1Manager) {
        return { status: 'not_initialized' };
    }
    
    return phase1Manager.getOptimizationMetrics();
}

/**
 * Deactivate Phase 1 systems (call this in your deactivate() function)
 */
async function deactivatePhase1() {
    if (phase1Manager) {
        console.log('🔄 Deactivating Phase 1 systems...');
        
        try {
            // Cleanup all systems
            for (const [systemName, system] of phase1Manager.systems.entries()) {
                if (typeof system.cleanup === 'function') {
                    await system.cleanup();
                }
            }
            
            phase1Manager = null;
            console.log('✅ Phase 1 systems deactivated');
            
        } catch (error) {
            console.error('❌ Error during Phase 1 deactivation:', error);
        }
    }
}

// EXAMPLE INTEGRATION IN MAIN EXTENSION.JS:
/*

// At the top of extension.js, add the Phase 1 integration
const { initializePhase1Optimizations, executeCommandWithPhase1, processAIRequestWithPhase1 } = require('./phase1-integration-example');

// In your activate function:
async function activate(context) {
    console.log('Vigthoria AI Coder is now active!');
    
    // Initialize Phase 1 optimizations
    await initializePhase1Optimizations(context);
    
    // Your existing initialization code...
    
    // Register commands with Phase 1 integration
    const askCommand = vscode.commands.registerCommand('vigthoria.ask', async () => {
        await executeCommandWithPhase1('vigthoria.ask', handleAskCommand);
    });
    
    const buildCommand = vscode.commands.registerCommand('vigthoria.build', async () => {
        await executeCommandWithPhase1('vigthoria.build', handleBuildCommand);
    });
    
    // Your existing code...
}

// In your deactivate function:
function deactivate() {
    // Deactivate Phase 1 systems
    deactivatePhase1();
    
    // Your existing deactivation code...
}

// Replace your AI processing calls with Phase 1 enhanced versions:
// OLD: const response = await callOllama(model, prompt);
// NEW: const response = await processAIRequestWithPhase1('ollama', model, prompt);

*/

module.exports = {
    initializePhase1Optimizations,
    executeCommandWithPhase1,
    processAIRequestWithPhase1,
    performFileOperationWithPhase1,
    getPhase1Status,
    getPhase1Metrics,
    deactivatePhase1,
    setupPhase1EventHandlers
};
