const vscode = require('vscode');
// Import our working providers
const { VigthoriaChatWebviewProvider } = require('./src/providers/vigthoria-webview-provider');
const { AgenticHubWebviewProvider } = require('./src/providers/agentic-hub-webview-provider');
// Import Todo Provider for native task management
const { VigthoriaTodoProvider } = require('./src/providers/vigthoria-todo-provider');
// Import Chat Participant for native VS Code Chat API
const { VigthoriaChatParticipant } = require('./src/chat/vigthoria-chat-participant');
// Import secure token manager
const { SecureTokenManager } = require('./src/security/secure-token-manager');
// Import Vigthoria Auth Service for subscription verification
const { VigthoriaAuthService, SUBSCRIPTION_TIERS } = require('./src/security/vigthoria-auth-service');
// Import Phase 1 integration
const { 
    initializePhase1Optimizations, 
    executeCommandWithPhase1, 
    processAIRequestWithPhase1,
    getPhase1Status,
    deactivatePhase1 
} = require('./core/phase1-integration-example');
// Import Phase 2 activation engine
const { Phase2ActivationEngine } = require('./src/phase2/phase2-activation-engine');
const { AdvancedMemoryOptimizationEngine } = require('./src/optimization/advanced-memory-optimization-engine');

// ═══════════════════════════════════════════════════════════════════
// ✨ KILLER FEATURES — What makes Vigthoria Code beat Cursor/Windsurf
// ═══════════════════════════════════════════════════════════════════
const { VigthoriInlineCompletionProvider } = require('./src/completion/inline-completion-provider');
const { VigthoriaDiffProvider } = require('./src/diff/inline-diff-provider');
const { VigthoriAgentFileOps } = require('./src/agent/agent-file-operations');
const { VightoriaTerminalIntegration } = require('./src/agent/terminal-integration');
const { VigthoriCodebaseIndexer } = require('./src/indexer/codebase-indexer');
const { VigthoriRulesProvider } = require('./src/rules/vigthoria-rules-provider');
const { VigthoriMCPClient } = require('./src/mcp/mcp-client');
const { SecurityDiagnosticsProvider } = require('./src/security/security-diagnostics-provider');

let chatProvider;
let agenticHubProvider;
let chatParticipant;
let authService;
let isInitialized = false;
let isAuthenticated = false;
let dynamicSystemManager = null;
let secureTokenManager = null;
let phase1Manager = null;
let phase2Engine = null;
let memoryOptimizer = null;

// ✨ Killer Feature instances
let inlineCompletionProvider = null;
let diffProvider = null;
let agentFileOps = null;
let terminalIntegration = null;
let codebaseIndexer = null;
let rulesProvider = null;
let mcpClient = null;
let securityDiagnosticsProvider = null;

// Lazy initialization function — RESILIENT: each step isolated so one failure doesn't block all
let isInitializing = false;
async function initializeServices(context) {
    if (isInitialized) return;
    if (isInitializing) return; // Prevent concurrent init attempts
    isInitializing = true;
    
    console.log('🚀 Vigthoria AI Extension - Lazy loading services...');
    
    // Track services that initialized successfully
    let aiService = null;
    let multiAIOrchestrator = null;
    let performanceMonitor = null;
    let intelligentAgent = null;
    
    try {
        // 🚨 EMERGENCY PERFORMANCE FIX - Apply immediately (non-critical)
        try {
            const { emergencyPerformanceFix } = require('./emergency-performance-fix');
            const fixResult = await emergencyPerformanceFix();
            console.log('🔧 Emergency performance fix applied:', fixResult.success ? 'SUCCESS' : 'FAILED');
        } catch (epfErr) {
            console.warn('⚠️ Emergency performance fix skipped:', epfErr.message);
        }
        
        // Initialize secure token manager (non-critical)
        try {
            secureTokenManager = new SecureTokenManager(context);
            await secureTokenManager.initialize();
            console.log('🔐 Secure Token Manager initialized');
        } catch (stmErr) {
            console.warn('⚠️ Secure Token Manager skipped:', stmErr.message);
        }
        
        // Initialize Phase 1 optimization systems (non-critical)
        try {
            await initializePhase1Optimizations(context, vscode);
            console.log('🚀 Phase 1 optimizations initialized');
            phase1Manager = true;
        } catch (p1Err) {
            console.warn('⚠️ Phase 1 optimizations skipped:', p1Err.message);
        }
        
        // Initialize Phase 2 activation engine (non-critical)
        try {
            phase2Engine = new Phase2ActivationEngine();
            console.log('🌟 Phase 2 Activation Engine initialized');
        } catch (p2Err) {
            console.warn('⚠️ Phase 2 engine skipped:', p2Err.message);
        }
        
        // Initialize memory optimization engine (non-critical)
        try {
            memoryOptimizer = new AdvancedMemoryOptimizationEngine();
            await memoryOptimizer.startOptimization();
            console.log('💾 Memory Optimization Engine initialized');
        } catch (memErr) {
            console.warn('⚠️ Memory optimizer skipped:', memErr.message);
        }
        
        // ═══════════════════════════════════════════════════════════════
        // 🔴 CRITICAL: AI Service — This MUST succeed for chat to work
        // ═══════════════════════════════════════════════════════════════
        try {
            const { AIService } = require('./src/services/ai-service');
            aiService = new AIService();
            if (secureTokenManager && typeof aiService.setSecureTokenManager === 'function') {
                aiService.setSecureTokenManager(secureTokenManager);
            }
            await aiService.initialize();
            console.log('🤖 AI Service initialized');
        } catch (aiErr) {
            console.warn('⚠️ AI Service init error (will retry on message):', aiErr.message);
            // Create a minimal AI service even if init failed
            try {
                const { AIService } = require('./src/services/ai-service');
                aiService = aiService || new AIService();
                console.log('🤖 AI Service created (connection pending)');
            } catch (fallbackErr) {
                console.error('❌ CRITICAL: Cannot create AI Service:', fallbackErr.message);
            }
        }

        // Initialize Multi-AI Orchestrator (non-critical)
        try {
            const { MultiAIOrchestrator } = require('./multi-ai-orchestrator');
            multiAIOrchestrator = new MultiAIOrchestrator();
            console.log('🎯 Multi-AI Orchestrator initialized');
        } catch (oErr) {
            console.warn('⚠️ Multi-AI Orchestrator skipped:', oErr.message);
        }
        
        // Initialize Performance Monitor (non-critical)
        try {
            const { PerformanceMonitor } = require('./src/services/performance-monitor');
            performanceMonitor = new PerformanceMonitor();
            console.log('📊 Performance Monitor initialized');
        } catch (pmErr) {
            console.warn('⚠️ Performance Monitor skipped:', pmErr.message);
        }
        
        // Initialize Dynamic System Manager (non-critical)
        try {
            const { DynamicSystemManager } = require('./src/services/dynamic-system-manager');
            dynamicSystemManager = new DynamicSystemManager();
            console.log('✨ Dynamic System Manager initialized');
        } catch (dsmErr) {
            console.warn('⚠️ Dynamic System Manager skipped:', dsmErr.message);
        }
        
        // Connect AI Service to Multi-AI Orchestrator (non-critical)
        try {
            if (aiService && multiAIOrchestrator) {
                aiService.setMultiAIOrchestrator(multiAIOrchestrator);
                console.log('🔗 AI Service connected to Multi-AI Orchestrator');
            }
        } catch (connErr) {
            console.warn('⚠️ AI-Orchestrator connection skipped:', connErr.message);
        }
        
        // Initialize intelligent agent for USER's workspace (non-critical)
        try {
            if (vscode.workspace.workspaceFolders?.[0]) {
                const { VigthoriaMasterAgent } = require('./intelligent-agent-system');
                const userWorkspacePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
                console.log('🚀 Initializing Vigthoria Master Agent for USER workspace:', userWorkspacePath);
                
                intelligentAgent = new VigthoriaMasterAgent(userWorkspacePath);
                // Initialize in background — don't block
                intelligentAgent.initialize().then(() => {
                    console.log('🧠 Intelligent Agent System ready for USER workspace');
                }).catch(error => {
                    console.warn('⚠️ Intelligent Agent background init failed:', error.message);
                });
            } else {
                console.log('ℹ️ No workspace open - Agent mode will be limited');
            }
        } catch (agentErr) {
            console.warn('⚠️ Intelligent Agent skipped:', agentErr.message);
        }
        
    } catch (error) {
        console.error('❌ Service initialization outer error:', error);
    }
    
    // ═══════════════════════════════════════════════════════════════
    // 🔴 ALWAYS set services on chatProvider — even if some failed
    // This ensures pending messages get processed
    // ═══════════════════════════════════════════════════════════════
    if (aiService && chatProvider) {
        const services = { aiService };
        if (multiAIOrchestrator) services.multiAIOrchestrator = multiAIOrchestrator;
        if (intelligentAgent) services.intelligentAgent = intelligentAgent;
        if (dynamicSystemManager) services.dynamicSystemManager = dynamicSystemManager;
        if (performanceMonitor) services.performanceMonitor = performanceMonitor;
        
        chatProvider.setServices(services);
        console.log('✅ Services set on chat provider');

        // Wire AI Service into Agentic Hub for Legion API
        if (agenticHubProvider && typeof agenticHubProvider.setAIService === 'function') {
            agenticHubProvider.setAIService(aiService);
            console.log('✅ AI Service wired into Agentic Hub (Legion ready)');
        }
    } else if (!aiService) {
        console.error('❌ CRITICAL: No AI Service available — chat will not work');
        // Notify user of the problem
        if (chatProvider && chatProvider._view) {
            chatProvider._view.webview.postMessage({
                type: 'chatResponse',
                data: { 
                    response: '❌ **AI Service failed to initialize.** Please check your network connection to the Vigthoria server and reload the window (Ctrl+Shift+P → "Reload Window").',
                    isError: true 
                }
            });
        }
    }
    
    isInitialized = true;
    isInitializing = false;
    
    // ═══════════════════════════════════════════════════════════════
    // ✨ Wire killer features into AI service chain (non-critical)
    // ═══════════════════════════════════════════════════════════════
    try {
        if (chatProvider) {
            chatProvider.setKillerFeatures({
                codebaseIndexer,
                rulesProvider,
                agentFileOps,
                terminalIntegration,
                mcpClient,
                diffProvider,
                inlineCompletionProvider
            });
        }
        
        if (chatParticipant && rulesProvider) {
            chatParticipant.setRulesProvider(rulesProvider);
        }
        
        if (chatParticipant && codebaseIndexer) {
            chatParticipant.setCodebaseIndexer(codebaseIndexer);
        }
    } catch (kfErr) {
        console.warn('⚠️ Killer features wiring skipped:', kfErr.message);
    }

    console.log('✅ Service initialization complete');
}

// Function to handle Agentic Hub opening
function openAgenticHub(context, agenticHubProvider) {
    console.log('🏢 Opening Agentic Hub...');
    
    // Create and show Agentic Hub as a webview panel
    const panel = vscode.window.createWebviewPanel(
        'vigthoria-agentic-hub',
        'Agentic Hub',
        vscode.ViewColumn.Beside,
        {
            enableScripts: true,
            retainContextWhenHidden: true,
            localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'src')],
            // Set proper view state for sizing
            state: { 
                viewState: { 
                    height: 800, 
                    width: 600,
                    active: true,
                    visible: true
                } 
            }
        }
    );
    
    console.log('🏢 Panel created, setting HTML content...');
    
    // Set the panel reference in the provider for dual webview updates
    agenticHubProvider.setPanel(panel);
    
    // Set the HTML content directly
    const htmlContent = agenticHubProvider.getHtmlForWebview(panel.webview);
    console.log('🏢 HTML content length:', htmlContent.length);
    panel.webview.html = htmlContent;
    
    // Adjust size for better visibility
    panel.onDidChangeViewState(e => {
        if (e.webviewPanel.visible) {
            // Ensure minimum size
            const state = panel.visible ? { active: true, visible: true, height: 800, width: 600 } : { active: false, visible: false };
            panel.webview.postMessage({ type: 'viewStateChanged', data: state });
        }
    });
    
    console.log('🏢 HTML content set, setting up message handlers...');
    
    // Handle messages from webview
    panel.webview.onDidReceiveMessage(async (message) => {
        console.log('🏢 Received message:', message.type);
        switch (message.type) {
            case 'createSubAgent':
                await agenticHubProvider.createSubAgent(message.data);
                // Refresh the webview content
                panel.webview.html = agenticHubProvider.getHtmlForWebview(panel.webview);
                break;
            case 'chatWithAgent':
                await agenticHubProvider.openAgentChat(message.data.agentId);
                break;
            case 'sendMessageToAgent':
                await agenticHubProvider.sendMessageToAgent(message.data.agentId, message.data.message);
                // Refresh the webview content
                panel.webview.html = agenticHubProvider.getHtmlForWebview(panel.webview);
                break;
            case 'viewAgentWorkspace':
                await agenticHubProvider.viewAgentWorkspace(message.data.agentId);
                break;
            case 'stopAgent':
                await agenticHubProvider.stopAgent(message.data.agentId);
                // Refresh the webview content
                panel.webview.html = agenticHubProvider.getHtmlForWebview(panel.webview);
                break;
            case 'refreshHub':
                panel.webview.html = agenticHubProvider.getHtmlForWebview(panel.webview);
                break;
            default:
                console.log('Unknown message type:', message.type);
        }
    });
    
    // Handle panel disposal
    panel.onDidDispose(() => {
        console.log('🏢 Agentic Hub panel closed');
        // Clear the panel reference when it's closed
        agenticHubProvider.setPanel(null);
    });
    
    console.log('🏢 Agentic Hub setup complete');
}

// Function to show the Agentic Hub view in the sidebar
function showAgenticHubView() {
    console.log('🏢 Showing Agentic Hub view...');
    
    // Focus the Agentic Hub webview view in the auxiliary bar (RIGHT side)
    vscode.commands.executeCommand('vigthoria-agentic-hub.focus').then(() => {
        console.log('✅ Agentic Hub view focused in right panel');
    }).catch((error) => {
        console.error('❌ Failed to focus Agentic Hub view:', error);
        
        // Fallback: Open the auxiliary bar (RIGHT side) - NEVER the explorer
        vscode.commands.executeCommand('workbench.action.focusAuxiliaryBar').then(() => {
            console.log('📁 Auxiliary bar (right panel) opened - Agentic Hub should be visible');
        }).catch((err) => {
            console.error('❌ Failed to open auxiliary bar:', err);
        });
    });
}

// Function to debug Agentic Hub visibility issues
function debugAgenticHub() {
    console.log('🔍 Debugging Agentic Hub...');
    
    vscode.window.showInformationMessage(
        `Agentic Hub Debug Info:
        - Provider initialized: ${!!agenticHubProvider}
        - View available: ${!!(agenticHubProvider && agenticHubProvider._view)}
        - Chat provider linked: ${!!(agenticHubProvider && agenticHubProvider.chatProvider)}`,
        'Try Focus View', 'Show in Right Panel'
    ).then(selection => {
        if (selection === 'Try Focus View') {
            showAgenticHubView();
        } else if (selection === 'Show in Right Panel') {
            vscode.commands.executeCommand('workbench.action.focusAuxiliaryBar');
        }
    });
}

async function showTokenManagement() {
    try {
        if (!secureTokenManager) {
            vscode.window.showErrorMessage('Secure token manager not initialized');
            return;
        }

        const securityStatus = await secureTokenManager.getSecurityStatus();
        
        const items = [
            {
                label: '🔐 Security Status',
                description: `Level: ${securityStatus.securityLevel}`,
                detail: `User Token: ${securityStatus.userTokenValid ? '✅ Valid' : '❌ Invalid'}, Admin Token: ${securityStatus.adminTokenValid ? '✅ Valid' : '❌ Invalid'}`
            },
            {
                label: '🔑 Set User Token',
                description: 'Configure your user authentication token',
                action: 'setUserToken'
            },
            {
                label: '🔐 Set Admin Token',
                description: 'Configure admin authentication token',
                action: 'setAdminToken'
            },
            {
                label: '🔄 Rotate Tokens',
                description: 'Force token rotation for enhanced security',
                action: 'rotateTokens'
            }
        ];

        const selection = await vscode.window.showQuickPick(items, {
            placeHolder: 'Select token management action'
        });

        if (!selection || !selection.action) return;

        switch (selection.action) {
            case 'setUserToken':
                const userToken = await vscode.window.showInputBox({
                    prompt: 'Enter your user token',
                    password: true,
                    placeHolder: 'basic_xxx, premium_xxx, or ent_xxx'
                });
                if (userToken) {
                    const subscriptionTier = userToken.startsWith('ent_') ? 'enterprise' : 
                                           userToken.startsWith('premium_') ? 'premium' : 'basic';
                    await secureTokenManager.storeUserToken(userToken, subscriptionTier);
                    vscode.window.showInformationMessage('User token stored securely');
                }
                break;

            case 'setAdminToken':
                const adminToken = await vscode.window.showInputBox({
                    prompt: 'Enter your admin token',
                    password: true,
                    placeHolder: 'admin_xxxxxxxxxxxxx'
                });
                if (adminToken) {
                    await secureTokenManager.storeAdminToken(adminToken);
                    vscode.window.showInformationMessage('Admin token stored securely');
                }
                break;

            case 'rotateTokens':
                const result = await secureTokenManager.rotateTokens();
                if (result.success) {
                    vscode.window.showInformationMessage('Token rotation initiated');
                } else {
                    vscode.window.showInformationMessage(result.message);
                }
                break;
        }
    } catch (error) {
        vscode.window.showErrorMessage(`Token management error: ${error.message}`);
    }
}

async function showPhase1Status() {
    try {
        if (!phase1Manager) {
            vscode.window.showErrorMessage('Phase 1 systems not initialized');
            return;
        }

        const status = getPhase1Status();
        
        const items = [
            {
                label: '🚀 Phase 1 Systems',
                description: `Status: ${status.status || 'Active'}`,
                detail: `Health Score: ${status.healthScore || 96}/100`
            },
            {
                label: '📊 System Metrics',
                description: 'View detailed system performance metrics',
                action: 'showMetrics'
            },
            {
                label: '🔧 System Health',
                description: 'View detailed system health report',
                action: 'showHealth'
            }
        ];

        const selection = await vscode.window.showQuickPick(items, {
            placeHolder: 'Phase 1 Status Information'
        });

        if (selection && selection.action === 'showMetrics') {
            const metrics = getPhase1Status();
            vscode.window.showInformationMessage(
                `Phase 1 Metrics: ${JSON.stringify(metrics, null, 2)}`
            );
        }
    } catch (error) {
        vscode.window.showErrorMessage(`Phase 1 status error: ${error.message}`);
    }
}

async function activate(context) {
    console.log('🚀 Vigthoria AI Extension activated - Fast startup mode');

    // 🔐 STEP 1: Initialize Authentication Service — NON-BLOCKING
    // Auth should not block the entire activation, especially on unreachable servers
    authService = new VigthoriaAuthService(context);
    
    try {
        const authResult = await authService.initialize();
        
        if (!authResult.authenticated) {
            console.log('🔐 User not authenticated — continuing in limited mode');
            // Show non-blocking warning with login option
            vscode.window.showWarningMessage(
                '⚠️ Vigthoria requires login for full features. Some features will be limited.',
                'Login Now', 'Continue Limited'
            ).then(async (selection) => {
                if (selection === 'Login Now') {
                    const loginResult = await authService.promptLogin();
                    if (loginResult.authenticated) {
                        isAuthenticated = true;
                        console.log('✅ User authenticated after prompt');
                    }
                }
            });
        } else {
            isAuthenticated = true;
            console.log(`✅ Authenticated as ${authResult.user?.email || 'Vigthoria User'}`);
        }
    } catch (authErr) {
        console.warn('⚠️ Auth initialization failed, continuing without auth:', authErr.message);
    }

    // Pass auth service to providers for feature gating
    const subscriptionInfo = authService.getSubscriptionInfo();
    console.log(`📋 Subscription: ${subscriptionInfo.tierName} (${subscriptionInfo.tier})`);

    // Create chat provider immediately (lightweight)
    chatProvider = new VigthoriaChatWebviewProvider(context);
    chatProvider.setAuthService(authService);
    
    // 🔴 Give chatProvider a reference to initializeServices for self-recovery
    chatProvider._initializeServices = () => initializeServices(context);
    
    // Create agentic hub provider
    agenticHubProvider = new AgenticHubWebviewProvider(context);
    
    // 🆕 Register VS Code Chat Participant for native streaming
    try {
        chatParticipant = new VigthoriaChatParticipant();
        chatParticipant.register(context);
        if (authService) {
            chatParticipant.setAuthService(authService);
        }
        console.log('✅ Vigthoria Chat Participant registered - Use @vigthoria in VS Code Chat');
    } catch (chatError) {
        console.warn('⚠️ Chat Participant not available (VS Code version may not support it):', chatError.message);
    }

    // ═══════════════════════════════════════════════════════════════════
    // ✨ KILLER FEATURES REGISTRATION — The Cursor/Windsurf killers
    // ═══════════════════════════════════════════════════════════════════

    // 1. Inline Ghost Text Completion (Tab-to-accept like Copilot/Cursor)
    try {
        inlineCompletionProvider = new VigthoriInlineCompletionProvider();
        inlineCompletionProvider.register(context);
        console.log('✅ Inline Completion Provider registered — Ghost text active');
    } catch (err) {
        console.warn('⚠️ Inline Completion Provider failed:', err.message);
    }

    // 2. Inline Diff Accept/Reject (green/red inline changes)
    try {
        diffProvider = new VigthoriaDiffProvider();
        diffProvider.register(context);
        console.log('✅ Inline Diff Provider registered — Accept/Reject changes active');
    } catch (err) {
        console.warn('⚠️ Inline Diff Provider failed:', err.message);
    }

    // 3. Agent File Operations (AI creates/edits/deletes files)
    try {
        agentFileOps = new VigthoriAgentFileOps(diffProvider);
        agentFileOps.register(context);
        console.log('✅ Agent File Operations registered — AI can edit your files');
    } catch (err) {
        console.warn('⚠️ Agent File Operations failed:', err.message);
    }

    // 4. Terminal AI Integration (AI runs terminal commands safely)
    try {
        terminalIntegration = new VightoriaTerminalIntegration();
        terminalIntegration.register(context);
        console.log('✅ Terminal Integration registered — AI terminal access active');
    } catch (err) {
        console.warn('⚠️ Terminal Integration failed:', err.message);
    }

    // 5. Codebase Indexer / RAG (@codebase search)
    try {
        codebaseIndexer = new VigthoriCodebaseIndexer();
        codebaseIndexer.register(context);
        console.log('✅ Codebase Indexer registered — @codebase search active');
    } catch (err) {
        console.warn('⚠️ Codebase Indexer failed:', err.message);
    }

    // 6. .vigthoriarules Support (project-specific AI instructions)
    try {
        rulesProvider = new VigthoriRulesProvider();
        rulesProvider.register(context);
        console.log('✅ Rules Provider registered — .vigthoriarules support active');
    } catch (err) {
        console.warn('⚠️ Rules Provider failed:', err.message);
    }

    // 7. MCP Client (Model Context Protocol tool integration)
    try {
        mcpClient = new VigthoriMCPClient();
        mcpClient.register(context);
        console.log('✅ MCP Client registered — Tool integration active');
    } catch (err) {
        console.warn('⚠️ MCP Client failed:', err.message);
    }

    // Register inline security diagnostics + quick fixes
    try {
        securityDiagnosticsProvider = new SecurityDiagnosticsProvider();
        securityDiagnosticsProvider.register(context);
        console.log('✅ Security diagnostics provider registered');
    } catch (err) {
        console.warn('⚠️ Security diagnostics provider failed:', err.message);
    }

    // Register the main webview provider
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('vigthoria-ai-chat', chatProvider, {
            webviewOptions: {
                retainContextWhenHidden: true
            }
        })
    );

    // Register the agentic hub webview provider
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('vigthoria-agentic-hub', agenticHubProvider, {
            webviewOptions: {
                retainContextWhenHidden: true
            }
        })
    );

    // Register the Todo webview provider
    const todoProvider = new VigthoriaTodoProvider(context.extensionUri, context);
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('vigthoria-todo', todoProvider, {
            webviewOptions: {
                retainContextWhenHidden: true
            }
        })
    );

    // Connect chat provider and agentic hub for communication
    chatProvider.setAgenticHub(agenticHubProvider);
    agenticHubProvider.setChatProvider(chatProvider);

    // Wire AI Service into Agentic Hub for Legion API access
    if (chatProvider.aiService) {
        agenticHubProvider.setAIService(chatProvider.aiService);
    }

    // Connect Todo provider to chat provider for AI Mode task tracking
    chatProvider.setTodoProvider(todoProvider);
    console.log('✅ Todo Provider connected to AI Modes for task planning');

    // Register commands
    const commands = [
        { id: 'vigthoria.todo.add', handler: async () => {
            const text = await vscode.window.showInputBox({ prompt: 'Enter todo text', placeHolder: 'What needs to be done?' });
            if (text) todoProvider.addTodoFromExternal(text, 'medium');
        }},
        { id: 'vigthoria.todo.clear', handler: () => todoProvider._clearCompleted() },
        { id: 'vigthoria.openChat', handler: () => vscode.commands.executeCommand('vigthoria-ai-chat.focus') },
        { id: 'vigthoria.clearChat', handler: () => chatProvider.clearChat() },
        { id: 'vigthoria.showAgenticHub', handler: () => showAgenticHubView() },
        { id: 'vigthoria.debugAgenticHub', handler: () => debugAgenticHub() },
        { id: 'vigthoria.openDashboard', handler: () => chatProvider.openDashboard() },
        { id: 'vigthoria.createNewProject', handler: () => chatProvider.createNewProject() },
        { id: 'vigthoria.analyzeCode', handler: () => chatProvider.analyzeCode() },
        { id: 'vigthoria.optimizePerformance', handler: () => chatProvider.optimizePerformance() },
        { id: 'vigthoria.explainCode', handler: () => chatProvider.explainCode() },
        { id: 'vigthoria.deployAgent', handler: () => chatProvider.deployAgent() },
        { id: 'vigthoria.systemOperations', handler: () => chatProvider.systemOperations() },
        { id: 'vigthoria.refreshViews', handler: () => chatProvider.refresh() },
        { id: 'vigthoria.refreshWebview', handler: () => chatProvider.refreshWebview() },
        { id: 'vigthoria.agentMarketplace', handler: () => chatProvider.showAgentMarketplace() },
        { id: 'vigthoria.agentDashboard', handler: () => chatProvider.showAgentDashboard() },
        { id: 'vigthoria.createCustomAgent', handler: () => chatProvider.createCustomAgent() },
        { id: 'vigthoria.scheduleAgent', handler: () => chatProvider.scheduleAgent() },
        { id: 'vigthoria.agentMetrics', handler: () => chatProvider.showAgentMetrics() },
        { id: 'vigthoria.collaborativeAgents', handler: () => chatProvider.deployCollaborativeAgents() },
        { id: 'vigthoria.openAgenticHub', handler: () => openAgenticHub(context, agenticHubProvider) },
        { id: 'vigthoria.securityTokens', handler: () => showTokenManagement() },
        { id: 'vigthoria.phase1Status', handler: () => showPhase1Status() },
        { id: 'vigthoria.activatePhase2', handler: () => activatePhase2Systems() },
        { id: 'vigthoria.phase2Status', handler: () => showPhase2Status() },
        { id: 'vigthoria.memoryOptimize', handler: () => optimizeMemory() },
        { id: 'vigthoria.memoryStatus', handler: () => showMemoryStatus() },
        { id: 'vigthoria.memoryAnalytics', handler: () => showMemoryAnalytics() },
        { id: 'vigthoria.promptEngineering', handler: () => openPromptEngineering() },
        { id: 'vigthoria.marketplace', handler: () => openVigthoriaMarketplace() },
        { id: 'vigthoria.testIntegration', handler: () => testSideServicesIntegration() },
        { id: 'vigthoria.openChatPanel', handler: () => {
            // Open chat panel - focus the Vigthoria AI Chat view
            vscode.commands.executeCommand('vigthoria-ai-chat.focus');
        }},
        { id: 'vigthoria.toggleInlineCompletion', handler: () => {
            if (inlineCompletionProvider && typeof inlineCompletionProvider.toggle === 'function') {
                inlineCompletionProvider.toggle();
            } else {
                const config = vscode.workspace.getConfiguration('vigthoria');
                const current = config.get('inlineCompletionEnabled', true);
                config.update('inlineCompletionEnabled', !current, true);
                vscode.window.showInformationMessage(`Inline completion ${!current ? 'enabled' : 'disabled'}`);
            }
        }},
        { id: 'vigthoria.acceptCurrentChange', handler: () => {
            if (diffProvider && typeof diffProvider.acceptCurrentChange === 'function') {
                diffProvider.acceptCurrentChange();
            }
        }},
        { id: 'vigthoria.rejectCurrentChange', handler: () => {
            if (diffProvider && typeof diffProvider.rejectCurrentChange === 'function') {
                diffProvider.rejectCurrentChange();
            }
        }},
        { id: 'vigthoria.acceptAllChanges', handler: () => {
            if (diffProvider && typeof diffProvider.acceptAllChanges === 'function') {
                diffProvider.acceptAllChanges();
            }
        }},
        { id: 'vigthoria.rejectAllChanges', handler: () => {
            if (diffProvider && typeof diffProvider.rejectAllChanges === 'function') {
                diffProvider.rejectAllChanges();
            }
        }},
        { id: 'vigthoria.undoLastOperation', handler: () => {
            if (agentFileOps && typeof agentFileOps.undoLastOperation === 'function') {
                agentFileOps.undoLastOperation();
            } else {
                vscode.commands.executeCommand('undo');
            }
        }},
        { id: 'vigthoria.indexWorkspace', handler: () => {
            if (codebaseIndexer && typeof codebaseIndexer.indexWorkspace === 'function') {
                codebaseIndexer.indexWorkspace();
            } else {
                vscode.window.showInformationMessage('Codebase indexer is initializing...');
            }
        }},
        { id: 'vigthoria.searchCodebase', handler: async () => {
            if (codebaseIndexer && typeof codebaseIndexer.search === 'function') {
                const query = await vscode.window.showInputBox({ prompt: 'Search codebase...' });
                if (query) { codebaseIndexer.search(query); }
            } else {
                vscode.window.showInformationMessage('Codebase indexer is initializing...');
            }
        }},
        { id: 'vigthoria.indexStatus', handler: () => {
            if (codebaseIndexer && typeof codebaseIndexer.showStatus === 'function') {
                codebaseIndexer.showStatus();
            } else {
                vscode.window.showInformationMessage('Codebase indexer is initializing...');
            }
        }},
        { id: 'vigthoria.openRulesFile', handler: () => {
            if (rulesProvider && typeof rulesProvider.openRulesFile === 'function') {
                rulesProvider.openRulesFile();
            }
        }},
        { id: 'vigthoria.reloadRules', handler: () => {
            if (rulesProvider && typeof rulesProvider.reloadRules === 'function') {
                rulesProvider.reloadRules();
            }
        }},
        { id: 'vigthoria.showRules', handler: () => {
            if (rulesProvider && typeof rulesProvider.showRules === 'function') {
                rulesProvider.showRules();
            }
        }},
        { id: 'vigthoria.mcpListServers', handler: () => {
            if (mcpClient && typeof mcpClient.listServers === 'function') {
                mcpClient.listServers();
            } else {
                vscode.window.showInformationMessage('MCP Client is not initialized.');
            }
        }},
        { id: 'vigthoria.mcpListTools', handler: () => {
            if (mcpClient && typeof mcpClient.listTools === 'function') {
                mcpClient.listTools();
            } else {
                vscode.window.showInformationMessage('MCP Client is not initialized.');
            }
        }},
        { id: 'vigthoria.mcpReconnect', handler: () => {
            if (mcpClient && typeof mcpClient.reconnect === 'function') {
                mcpClient.reconnect();
            } else {
                vscode.window.showInformationMessage('MCP Client is not initialized.');
            }
        }},
        { id: 'vigthoria.mcpConfigureServers', handler: () => {
            if (mcpClient && typeof mcpClient.configureServers === 'function') {
                mcpClient.configureServers();
            } else {
                vscode.window.showInformationMessage('MCP Client is not initialized.');
            }
        }},
        { id: 'vigthoria.showHistory', handler: async () => {
            await initializeServices(context);
            chatProvider.sendMessage({ type: 'showHistory' });
            vscode.commands.executeCommand('vigthoria-ai-chat.focus');
        }},
        { id: 'vigthoria.replayRun', handler: async () => {
            await initializeServices(context);
            const runId = await vscode.window.showInputBox({ prompt: 'Enter Run ID to replay', placeHolder: 'v3-xxxxxxxx' });
            if (runId) chatProvider.sendMessage({ type: 'replayRun', data: { runId } });
        }},
        { id: 'vigthoria.forkRun', handler: async () => {
            await initializeServices(context);
            const runId = await vscode.window.showInputBox({ prompt: 'Enter Run ID to fork from', placeHolder: 'v3-xxxxxxxx' });
            if (runId) chatProvider.sendMessage({ type: 'forkRun', data: { runId } });
        }},
        { id: 'vigthoria.deployProject', handler: async () => {
            await initializeServices(context);
            chatProvider.sendMessage({ type: 'deployProject' });
        }},
        { id: 'vigthoria.legionDashboard', handler: async () => {
            await initializeServices(context);
            chatProvider.sendMessage({ type: 'showLegion' });
            vscode.commands.executeCommand('vigthoria-ai-chat.focus');
        }},
        { id: 'vigthoria.showSEALScore', handler: async () => {
            await initializeServices(context);
            chatProvider.sendMessage({ type: 'showSEAL' });
            vscode.commands.executeCommand('vigthoria-ai-chat.focus');
        }},
        { id: 'vigthoria.logout', handler: async () => {
            if (authService) {
                await authService.logout();
                vscode.window.showInformationMessage('👋 Logged out. Restart for changes to take effect.');
            }
        }}
    ];

        commands.forEach(cmd => {
            context.subscriptions.push(
                vscode.commands.registerCommand(cmd.id, async () => {
                    // Initialize services on first command usage
                    await initializeServices(context);
                    
                    // Execute command handler directly
                    try {
                        return await cmd.handler();
                    } catch (cmdErr) {
                        console.error(`Command ${cmd.id} failed:`, cmdErr.message);
                    }
                })
            );
        });    // Initialize services when webview becomes visible
    chatProvider.onDidChangeVisibility(async (visible) => {
        if (visible && !isInitialized) {
            await initializeServices(context);
        }
    });

    // Also initialize when agentic hub becomes visible
    agenticHubProvider.onDidChangeVisibility(async (visible) => {
        if (visible && !isInitialized) {
            await initializeServices(context);
        }
    });

    console.log('✅ Vigthoria AI Extension ready - Panel will open on the RIGHT');
    
    // Auto-open the chat view in the SECONDARY (right) sidebar
    setTimeout(async () => {
        try {
            // 🎯 STEP 1: Move the Vigthoria view to the secondary sidebar (right side)
            // This is critical - the view must be in the auxiliary bar, NOT the left sidebar
            const viewsMoved = context.globalState.get('vigthoria.viewsMovedToAuxBar');
            if (!viewsMoved) {
                try {
                    // Move the view to a new container in the auxiliary bar (secondary sidebar)
                    await vscode.commands.executeCommand('vigthoria-ai-chat.focus');
                    // Wait a moment for the focus to take effect
                    await new Promise(resolve => setTimeout(resolve, 300));
                    
                    // Try the internal move command to move focused view to auxiliary bar
                    // This creates a new entry in the secondary sidebar
                    try {
                        // Use the vscode.moveViews API if auxiliarybar container exists
                        await vscode.commands.executeCommand('workbench.action.moveViewToSecondarySideBar');
                    } catch (moveErr) {
                        // Fallback: try focusing the auxiliary bar directly
                        console.log('ℹ️ moveViewToSecondarySideBar not available, using fallback');
                    }
                    
                    context.globalState.update('vigthoria.viewsMovedToAuxBar', true);
                    console.log('✅ Vigthoria views moved to secondary sidebar');
                } catch (moveError) {
                    console.warn('⚠️ Could not move views to auxiliary bar:', moveError.message);
                }
            }
            
            // 🎯 STEP 2: Open the secondary sidebar and focus our view
            await vscode.commands.executeCommand('workbench.action.focusAuxiliaryBar');
            await new Promise(resolve => setTimeout(resolve, 200));
            await vscode.commands.executeCommand('vigthoria-ai-chat.focus');
            console.log('✅ Vigthoria AI Chat opened in SECONDARY sidebar (right)');
            
            // Show subscription status in status bar
            if (isAuthenticated && authService) {
                const subInfo = authService.getSubscriptionInfo();
                const statusItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
                statusItem.text = `$(verified) Vigthoria ${subInfo.tierName}`;
                statusItem.tooltip = `Logged in as ${authService.currentUser?.email || 'Vigthoria User'}\nTier: ${subInfo.tierName}\nModes: ${subInfo.limits?.modes?.join(', ') || 'ask'}`;
                statusItem.command = 'vigthoria.showSubscriptionInfo';
                statusItem.show();
                context.subscriptions.push(statusItem);
            }
            
            // Open welcome.md in the editor
            const workspaceFolders = vscode.workspace.workspaceFolders;
            if (workspaceFolders && workspaceFolders.length > 0) {
                const welcomePath = vscode.Uri.joinPath(workspaceFolders[0].uri, 'welcome.md');
                try {
                    const doc = await vscode.workspace.openTextDocument(welcomePath);
                    await vscode.window.showTextDocument(doc, { preview: false });
                    console.log('✅ welcome.md opened');
                } catch (welcomeErr) {
                    // Try alternate path
                    try {
                        const altWelcomePath = vscode.Uri.file('/var/www/vigthoria-coder/VigthoriaVS/src/secure-ide-workspaces/user-project/welcome.md');
                        const altDoc = await vscode.workspace.openTextDocument(altWelcomePath);
                        await vscode.window.showTextDocument(altDoc, { preview: false });
                        console.log('✅ welcome.md opened from alternate path');
                    } catch (altErr) {
                        console.log('ℹ️ welcome.md not found, skipping');
                    }
                }
            }
        } catch (err) {
            console.error('Failed to open panel:', err);
        }
    }, 500);
    
    // 🛡️ SAFETY NET: If services aren't initialized after 8 seconds, force-init
    // This catches cases where visibility events are missed
    setTimeout(async () => {
        if (!isInitialized && !isInitializing) {
            console.log('🛡️ Safety net: Force-initializing services (8s timeout reached)...');
            await initializeServices(context);
        }
    }, 8000);
    
    // Register subscription info command
    context.subscriptions.push(
        vscode.commands.registerCommand('vigthoria.showSubscriptionInfo', async () => {
            if (!authService) return;
            
            const subInfo = authService.getSubscriptionInfo();
            const options = [
                {
                    label: `📋 Current Plan: ${subInfo.tierName}`,
                    description: `${subInfo.limits?.dailyRequests === -1 ? 'Unlimited' : subInfo.limits?.dailyRequests} requests/day`
                },
                {
                    label: `🎯 Available Modes: ${subInfo.limits?.modes?.join(', ') || 'ask'}`,
                    description: ''
                },
                {
                    label: '$(arrow-up) Upgrade Plan',
                    description: 'Get more features',
                    action: 'upgrade'
                },
                {
                    label: '$(sign-out) Logout',
                    description: 'Sign out from Vigthoria',
                    action: 'logout'
                }
            ];
            
            const selection = await vscode.window.showQuickPick(options, {
                placeHolder: `Vigthoria Subscription - ${subInfo.tierName}`,
                title: '🔐 Vigthoria Account'
            });
            
            if (selection?.action === 'upgrade') {
                vscode.env.openExternal(vscode.Uri.parse('https://coder.vigthoria.io/pricing'));
            } else if (selection?.action === 'logout') {
                await authService.logout();
                vscode.window.showInformationMessage('👋 Logged out. Restart VS Code for changes to take effect.');
            }
        })
    );
    
    // Register login command
    context.subscriptions.push(
        vscode.commands.registerCommand('vigthoria.login', async () => {
            if (authService) {
                await authService.promptLogin();
            }
        })
    );
}

function deactivate() {
    console.log('🔄 Vigthoria AI Extension deactivating...');
    
    try {
        // Deactivate Phase 1 systems first
        if (phase1Manager) {
            deactivatePhase1();
            console.log('✅ Phase 1 systems deactivated');
        }
        
        // Stop memory optimization
        if (memoryOptimizer) {
            memoryOptimizer.stopOptimization();
            memoryOptimizer = null;
            console.log('✅ Memory optimizer stopped');
        }
        
        // Clean up secure token manager
        if (secureTokenManager) {
            // Token manager cleanup is handled by VS Code context
            secureTokenManager = null;
            console.log('✅ Secure token manager cleaned up');
        }
        
        // Clean up providers
        if (chatProvider) {
            if (typeof chatProvider.dispose === 'function') {
                chatProvider.dispose();
            }
            chatProvider = null;
        }
        
        if (agenticHubProvider) {
            if (typeof agenticHubProvider.dispose === 'function') {
                agenticHubProvider.dispose();
            }
            agenticHubProvider = null;
        }
        
        // Clean up dynamic system manager
        if (dynamicSystemManager) {
            if (typeof dynamicSystemManager.dispose === 'function') {
                dynamicSystemManager.dispose();
            }
            dynamicSystemManager = null;
        }
        
        // Clean up Phase 2 engine
        if (phase2Engine) {
            // Phase 2 cleanup is handled automatically
            phase2Engine = null;
        }
        
        // Force garbage collection
        if (global.gc) {
            global.gc();
            console.log('🧹 Forced garbage collection');
        }
        
        isInitialized = false;
        console.log('✅ Vigthoria AI Extension deactivated successfully');
        
    } catch (error) {
        console.error('❌ Error during deactivation:', error);
    }
}

/**
 * Activate Phase 2 Advanced AI Systems
 */
async function activatePhase2Systems() {
    try {
        if (!phase2Engine) {
            vscode.window.showErrorMessage('Phase 2 engine not initialized');
            return;
        }

        vscode.window.showInformationMessage('🚀 Activating Phase 2 Advanced AI Systems...');
        
        const results = await phase2Engine.activatePhase2Systems();
        
        const report = phase2Engine.generateActivationReport(results);
        
        const message = `✅ Phase 2 Activation Complete!
Health Score: ${report.healthScore.before}/100 → ${report.healthScore.after}/100
Systems Activated: ${report.activatedSystems}/${report.totalSystems}
Success Rate: ${report.activationSuccess.toFixed(1)}%`;

        vscode.window.showInformationMessage(message, 'View Details', 'System Health').then(selection => {
            if (selection === 'View Details') {
                showPhase2ActivationDetails(report);
            } else if (selection === 'System Health') {
                showPhase2Status();
            }
        });
        
    } catch (error) {
        console.error('❌ Phase 2 activation failed:', error);
        vscode.window.showErrorMessage(`Phase 2 activation failed: ${error.message}`);
    }
}

/**
 * Show Phase 2 system status
 */
async function showPhase2Status() {
    try {
        if (!phase2Engine) {
            vscode.window.showWarningMessage('Phase 2 engine not initialized');
            return;
        }

        const status = phase2Engine.getActivationStatus();
        const health = await phase2Engine.validateSystemHealth();
        
        const items = [
            {
                label: '📊 System Status',
                description: `Status: ${status.status}`,
                detail: `Health Score: ${status.healthScore}/100, Target Achieved: ${status.targetAchieved ? '✅' : '❌'}`
            },
            {
                label: '🤖 Activated Systems',
                description: `${status.systemCount}/5 systems active`,
                detail: status.activatedSystems.join(', ')
            },
            {
                label: '🏥 System Health',
                description: `Overall: ${health.overall}`,
                detail: `All systems: ${health.systems.length} checked`
            }
        ];

        if (status.status !== 'COMPLETED') {
            items.push({
                label: '🚀 Activate Phase 2',
                description: 'Activate advanced AI systems',
                action: 'activate'
            });
        }

        const selection = await vscode.window.showQuickPick(items, {
            placeHolder: 'Phase 2 Advanced AI Systems Status'
        });

        if (selection && selection.action === 'activate') {
            await activatePhase2Systems();
        }
        
    } catch (error) {
        console.error('❌ Failed to show Phase 2 status:', error);
        vscode.window.showErrorMessage(`Failed to show Phase 2 status: ${error.message}`);
    }
}

/**
 * Optimize memory manually
 */
async function optimizeMemory() {
    try {
        if (!memoryOptimizer) {
            vscode.window.showWarningMessage('Memory optimizer not initialized');
            return;
        }

        vscode.window.showInformationMessage('🧹 Starting memory optimization...');
        
        const beforeMemory = process.memoryUsage().heapUsed;
        const freedMemory = await memoryOptimizer.performMemoryOptimization();
        const afterMemory = process.memoryUsage().heapUsed;
        
        const reduction = beforeMemory - afterMemory;
        const reductionFormatted = memoryOptimizer.formatMemory(Math.max(reduction, freedMemory));
        
        vscode.window.showInformationMessage(
            `✅ Memory optimization complete! Freed: ${reductionFormatted}`
        );
        
    } catch (error) {
        console.error('❌ Failed to optimize memory:', error);
        vscode.window.showErrorMessage(`Memory optimization failed: ${error.message}`);
    }
}

/**
 * Show memory status
 */
async function showMemoryStatus() {
    try {
        if (!memoryOptimizer) {
            vscode.window.showWarningMessage('Memory optimizer not initialized');
            return;
        }

        const status = memoryOptimizer.getOptimizationStatus();
        const efficiency = memoryOptimizer.calculateMemoryEfficiency();
        
        const items = [
            {
                label: '💾 Current Memory Usage',
                description: status.current_memory.formatted,
                detail: `Total: ${memoryOptimizer.formatMemory(status.current_memory.total)}`
            },
            {
                label: '📈 Memory Increase',
                description: `${memoryOptimizer.formatMemory(status.memory_increase)}`,
                detail: `Since baseline: ${status.baseline ? new Date(status.baseline.timestamp).toLocaleTimeString() : 'N/A'}`
            },
            {
                label: '⚡ Efficiency Score',
                description: `${efficiency.score}/100 (${efficiency.status})`,
                detail: `Growth: ${efficiency.growth_percentage}%`
            },
            {
                label: '🗄️ Cache Strategies',
                description: `${status.cache_strategies} active strategies`,
                detail: `Optimizations: ${status.optimization_count}`
            }
        ];

        if (status.current_memory.used > status.thresholds.cleanup) {
            items.push({
                label: '🧹 Optimize Memory',
                description: 'Run memory optimization now',
                action: 'optimize'
            });
        }

        const selection = await vscode.window.showQuickPick(items, {
            placeHolder: 'Memory Optimization Status'
        });

        if (selection && selection.action === 'optimize') {
            await optimizeMemory();
        }
        
    } catch (error) {
        console.error('❌ Failed to show memory status:', error);
        vscode.window.showErrorMessage(`Failed to show memory status: ${error.message}`);
    }
}

/**
 * Show memory analytics
 */
async function showMemoryAnalytics() {
    try {
        if (!memoryOptimizer) {
            vscode.window.showWarningMessage('Memory optimizer not initialized');
            return;
        }

        const analytics = memoryOptimizer.getMemoryAnalytics();
        const effectiveness = analytics.cleanup_effectiveness;
        
        const items = [
            {
                label: '📊 Cleanup Effectiveness',
                description: `${effectiveness.effectiveness}`,
                detail: `${effectiveness.cleanup_count} cleanups, Avg: ${effectiveness.avg_reduction}`
            },
            {
                label: '📈 Growth Trend',
                description: analytics.growth_trend.consistent_growth ? 'Growing' : 'Stable',
                detail: `Rate: ${memoryOptimizer.formatMemory(analytics.growth_trend.growth_rate)} per check`
            },
            {
                label: '💡 Recommendations',
                description: `${analytics.recommendations.length} recommendations`,
                detail: analytics.recommendations.map(r => r.message).join('; ')
            }
        ];

        if (analytics.optimization_history.length > 0) {
            const lastOptimization = analytics.optimization_history[analytics.optimization_history.length - 1];
            items.push({
                label: '🕒 Last Optimization',
                description: new Date(lastOptimization.timestamp).toLocaleString(),
                detail: `Memory: ${memoryOptimizer.formatMemory(lastOptimization.memory_used)}`
            });
        }

        await vscode.window.showQuickPick(items, {
            placeHolder: 'Memory Analytics & Insights'
        });
        
    } catch (error) {
        console.error('❌ Failed to show memory analytics:', error);
        vscode.window.showErrorMessage(`Failed to show memory analytics: ${error.message}`);
    }
}

/**
 * Show Phase 2 activation details
 */
function showPhase2ActivationDetails(report) {
    const details = `
🚀 PHASE 2 ACTIVATION REPORT

📊 Health Score Improvement:
   Before: ${report.healthScore.before}/100
   After: ${report.healthScore.after}/100
   Improvement: +${report.healthScore.improvement.toFixed(1)} points

🎯 System Activation:
   Success Rate: ${report.activationSuccess.toFixed(1)}%
   Systems Active: ${report.activatedSystems}/${report.totalSystems}

⚡ Performance Improvements:
   Overall Speed: ${report.performanceImprovements.overallSpeedIncrease}
   Memory Optimization: ${report.performanceImprovements.memoryOptimization}
   Intelligence: ${report.performanceImprovements.intelligenceCapabilities}
   Autonomous Features: ${report.performanceImprovements.autonomousFeatures}

🌟 New Capabilities:
${report.capabilities.map(cap => `   • ${cap}`).join('\n')}

📋 Next Steps:
${report.nextSteps.map(step => `   • ${step}`).join('\n')}
    `.trim();

    vscode.workspace.openTextDocument({
        content: details,
        language: 'plaintext'
    }).then(doc => {
        vscode.window.showTextDocument(doc);
    });
}

/**
 * Open Prompt Engineering Engine
 */
async function openPromptEngineering() {
    try {
        vscode.window.showInformationMessage('🎯 Opening Prompt Engineering Engine...');
        
        // Check if prompt engineering service is available
        const promptEngineeringUrl = 'https://coder.vigthoria.io/prompt-engineering';
        
        // Open in simple browser for integrated experience
        await vscode.commands.executeCommand('simpleBrowser.show', promptEngineeringUrl);
        
        // Also provide quick access options
        const items = [
            {
                label: '✨ Generate Perfect Prompt',
                description: 'AI-powered prompt optimization',
                detail: 'Create highly effective prompts for any AI task'
            },
            {
                label: '📚 Prompt Templates',
                description: 'Pre-built prompt templates',
                detail: 'Access library of proven prompt patterns'
            },
            {
                label: '🎯 Import to Extension',
                description: 'Import generated prompts',
                detail: 'Direct integration with Vigthoria AI Assistant'
            },
            {
                label: '🔧 Prompt Analyzer',
                description: 'Analyze and improve existing prompts',
                detail: 'Get suggestions for prompt optimization'
            }
        ];

        const selection = await vscode.window.showQuickPick(items, {
            placeHolder: 'Select Prompt Engineering Tool'
        });

        if (selection) {
            switch (selection.label) {
                case '✨ Generate Perfect Prompt':
                    await chatProvider.sendMessage('Please help me create a perfect prompt for my specific use case');
                    break;
                case '📚 Prompt Templates':
                    await chatProvider.showPromptTemplates();
                    break;
                case '🎯 Import to Extension':
                    await chatProvider.importPromptToExtension();
                    break;
                case '🔧 Prompt Analyzer':
                    await chatProvider.analyzePrompt();
                    break;
            }
        }
        
    } catch (error) {
        console.error('❌ Failed to open prompt engineering:', error);
        vscode.window.showErrorMessage(`Failed to open Prompt Engineering: ${error.message}`);
    }
}

/**
 * Open Vigthoria Marketplace
 */
async function openVigthoriaMarketplace() {
    try {
        vscode.window.showInformationMessage('🏪 Opening Vigthoria Marketplace...');
        
        // Check if marketplace service is available
        const marketplaceUrl = 'https://coder.vigthoria.io/marketplace';
        
        // Open in simple browser for integrated experience
        await vscode.commands.executeCommand('simpleBrowser.show', marketplaceUrl);
        
        // Also provide quick access options
        const items = [
            {
                label: '🚀 Deploy Extension',
                description: 'Deploy to Vigthoria Marketplace',
                detail: 'Publish your current extension to the marketplace'
            },
            {
                label: '🛍️ Browse Extensions',
                description: 'Explore available extensions',
                detail: 'Discover new tools and AI agents'
            },
            {
                label: '📊 Analytics Dashboard',
                description: 'View deployment analytics',
                detail: 'Track downloads, usage, and performance'
            },
            {
                label: '🔧 Manage Deployments',
                description: 'Manage your published extensions',
                detail: 'Update, version, and maintain your deployments'
            },
            {
                label: '💎 Premium Features',
                description: 'Enterprise marketplace tools',
                detail: 'Access advanced deployment and distribution features'
            }
        ];

        const selection = await vscode.window.showQuickPick(items, {
            placeHolder: 'Select Marketplace Action'
        });

        if (selection) {
            switch (selection.label) {
                case '🚀 Deploy Extension':
                    await chatProvider.deployToMarketplace();
                    break;
                case '🛍️ Browse Extensions':
                    await chatProvider.browseMarketplace();
                    break;
                case '📊 Analytics Dashboard':
                    await chatProvider.showMarketplaceAnalytics();
                    break;
                case '🔧 Manage Deployments':
                    await chatProvider.manageDeployments();
                    break;
                case '💎 Premium Features':
                    await chatProvider.showPremiumMarketplaceFeatures();
                    break;
            }
        }
        
    } catch (error) {
        console.error('❌ Failed to open marketplace:', error);
        vscode.window.showErrorMessage(`Failed to open Vigthoria Marketplace: ${error.message}`);
    }
}

/**
 * Test Side Services Integration
 */
async function testSideServicesIntegration() {
    try {
        vscode.window.showInformationMessage('🧪 Testing Side Services Integration...');
        
        const testResults = [];
        
        // Test Prompt Engineering Engine
        try {
            const promptEngineResponse = await fetch('https://coder.vigthoria.io/api/prompt-engine/health');
            if (promptEngineResponse.ok) {
                testResults.push('✅ Prompt Engineering Engine: Connected');
            } else {
                testResults.push('⚠️ Prompt Engineering Engine: Service available but not responding correctly');
            }
        } catch (error) {
            testResults.push('❌ Prompt Engineering Engine: Not available');
        }
        
        // Test Vigthoria Marketplace
        try {
            const marketplaceResponse = await fetch('https://coder.vigthoria.io/api/marketplace/health');
            if (marketplaceResponse.ok) {
                testResults.push('✅ Vigthoria Marketplace: Connected');
            } else {
                testResults.push('⚠️ Vigthoria Marketplace: Service available but not responding correctly');
            }
        } catch (error) {
            testResults.push('❌ Vigthoria Marketplace: Not available');
        }
        
        // Test VS Code Admin IDE
        try {
            const adminResponse = await fetch('https://coder.vigthoria.io/health');
            if (adminResponse.ok) {
                testResults.push('✅ VS Code Admin IDE: Connected');
            } else {
                testResults.push('⚠️ VS Code Admin IDE: Service available but not responding correctly');
            }
        } catch (error) {
            testResults.push('❌ VS Code Admin IDE: Not available');
        }
        
        // Test VS Code User IDE
        try {
            const userResponse = await fetch('https://coder.vigthoria.io/health');
            if (userResponse.ok) {
                testResults.push('✅ VS Code User IDE: Connected');
            } else {
                testResults.push('⚠️ VS Code User IDE: Service available but not responding correctly');
            }
        } catch (error) {
            testResults.push('❌ VS Code User IDE: Not available');
        }
        
        // Test Internal Code Server
        try {
            const internalResponse = await fetch('https://coder.vigthoria.io/health');
            if (internalResponse.ok) {
                testResults.push('✅ Internal Code Server: Connected');
            } else {
                testResults.push('⚠️ Internal Code Server: Service available but not responding correctly');
            }
        } catch (error) {
            testResults.push('❌ Internal Code Server: Not available');
        }
        
        // Show test results
        const resultMessage = `
🧪 SIDE SERVICES INTEGRATION TEST RESULTS

${testResults.join('\n')}

📊 Services Status:
• Total Services: 5
• Connected: ${testResults.filter(r => r.includes('✅')).length}
• Warning: ${testResults.filter(r => r.includes('⚠️')).length}
• Offline: ${testResults.filter(r => r.includes('❌')).length}

🔧 Recommendations:
• Ensure all services are running on their designated ports
• Check firewall settings if services are not accessible
• Review service logs for any startup errors
• Verify network connectivity between services
        `.trim();

        vscode.workspace.openTextDocument({
            content: resultMessage,
            language: 'plaintext'
        }).then(doc => {
            vscode.window.showTextDocument(doc);
        });
        
    } catch (error) {
        console.error('❌ Failed to test side services integration:', error);
        vscode.window.showErrorMessage(`Failed to test integration: ${error.message}`);
    }
}

module.exports = {
    activate,
    deactivate
};