/**
 * 🚀 MULTI-AI ORCHESTRATION SYSTEM
 * Advanced coordination of multiple AI models for optimal results
 */

class MultiAIOrchestrator {
    constructor() {
        this.aiModels = new Map([
            ['creativity', {
                models: ['llama3:70b', 'mixtral:8x7b-instruct-v0.1-q4_K_M', 'qwen:72b-chat-q4_K_M'],
                capabilities: ['creative_writing', 'brainstorming', 'innovative_solutions'],
                priority: 1
            }],
            ['optimization', {
                models: ['deepseek-coder-v2:latest', 'qwen2.5-coder:32b', 'starcoder2:15b'],
                capabilities: ['code_optimization', 'performance_tuning', 'algorithm_improvement'],
                priority: 2
            }],
            ['debugging', {
                models: ['deepseek-coder:33b-instruct-q4_K_M', 'codellama:34b-instruct-q4_K_M', 'phi3:mini'],
                capabilities: ['bug_detection', 'error_analysis', 'fix_generation'],
                priority: 3
            }],
            ['architecture', {
                models: ['llama3:70b', 'qwen2.5-coder:32b', 'mixtral:8x7b-instruct-v0.1-q4_K_M'],
                capabilities: ['system_design', 'architecture_planning', 'scalability_analysis'],
                priority: 1
            }],
            ['security', {
                models: ['llama3:70b', 'deepseek-coder-v2:latest', 'mixtral:8x7b-instruct-v0.1-q4_K_M'],
                capabilities: ['vulnerability_detection', 'security_analysis', 'penetration_testing'],
                priority: 2
            }],
            ['documentation', {
                models: ['llama3:8b-instruct-q4_0', 'qwen2.5-coder:32b', 'mistral-openorca:latest'],
                capabilities: ['documentation_generation', 'api_docs', 'code_explanation'],
                priority: 3
            }],
            ['testing', {
                models: ['codellama:13b-instruct-q4_K_M', 'deepseek-coder:6.7b-instruct-q4_0', 'starcoder2:7b'],
                capabilities: ['test_generation', 'test_automation', 'coverage_analysis'],
                priority: 2
            }]
        ]);
        
        this.orchestrationHistory = [];
        this.modelPerformance = new Map();
        this.taskQueue = [];
        this.runningTasks = new Map();
    }

    /**
     * Process a user message and determine appropriate response strategy
     */
    async processMessage(messageText, options = {}) {
        const { mode = 'ask', subscription = 'BASIC', isAdmin = false, statusCallback = null } = options;
        
        try {
            // Analyze message complexity and type
            const messageAnalysis = this.analyzeMessage(messageText, mode);
            
            // Handle AGENT mode - delegate to external service
            if (mode.toLowerCase() === 'agent') {
                return await this.processAgentMode(messageText, messageAnalysis, options);
            }
            
            // Handle OPERATOR mode - delegate to external service
            if (mode.toLowerCase() === 'operator') {
                return await this.processOperatorMode(messageText, messageAnalysis, options);
            }
            
            // For simple messages, use direct processing
            if (messageAnalysis.complexity === 'simple') {
                return await this.processSimpleMessage(messageText, mode, messageAnalysis, options);
            }
            
            // For complex tasks, use multi-AI orchestration
            if (messageAnalysis.complexity === 'complex') {
                const task = {
                    text: messageText,
                    mode: mode,
                    context: messageAnalysis,
                    userContext: { subscription, isAdmin },
                    timestamp: new Date().toISOString()
                };
                
                return await this.processComplexTask(task, options);
            }
            
            // Default processing
            return await this.processStandardMessage(messageText, mode, messageAnalysis, options);
            
        } catch (error) {
            console.error('Error in processMessage:', error);
            return {
                success: false,
                error: error.message,
                response: `I encountered an error processing your message: ${error.message}`
            };
        }
    }

    /**
     * Analyze message to determine complexity and type
     */
    analyzeMessage(message, mode) {
        const complexityIndicators = {
            high: ['create', 'build', 'implement', 'design', 'architecture', 'system', 'integrate', 'optimize'],
            medium: ['explain', 'analyze', 'debug', 'fix', 'review', 'refactor'],
            low: ['what', 'how', 'why', 'show', 'example']
        };
        
        let complexity = 'simple';
        const lowerMessage = message.toLowerCase();
        
        if (complexityIndicators.high.some(keyword => lowerMessage.includes(keyword))) {
            complexity = 'complex';
        } else if (complexityIndicators.medium.some(keyword => lowerMessage.includes(keyword))) {
            complexity = 'medium';
        }
        
        return {
            complexity,
            type: this.categorizeMessage(message, mode),
            keywords: this.extractKeywords(message),
            intent: this.determineIntent(message, mode)
        };
    }

    /**
     * Process simple messages quickly
     */
    async processSimpleMessage(message, mode, analysis, options = {}) {
        console.log(`🤖 Vigthoria processSimpleMessage: ${message}...`);
        
        try {
            // Update context manager mode
            if (this.contextManager) {
                this.contextManager.updateMode(mode.toUpperCase());
            }

            // For ASK and BUILD modes, use Ollama LLM with Vigthoria context
            if (mode.toLowerCase() === 'ask' || mode.toLowerCase() === 'build') {
                return await this.processVigthortiaMode(message, mode, analysis, options);
            }

            // Default fallback for other simple modes
            return {
                success: true,
                response: `Hello! I'm Vigthoria, your AI programming assistant. I understand you want help with: "${message}". This appears to be a ${analysis.complexity} task. Let me assist you with that.`,
                type: 'simple',
                source: 'vigthoria-basic',
                analysis: analysis
            };

        } catch (error) {
            console.error(`❌ Vigthoria processSimpleMessage error: ${error}`);
            return this.fallbackToVigthoria(message, mode, error);
        }
    }

    /**
     * Process standard messages with basic AI
     */
    async processStandardMessage(message, mode, analysis, options = {}) {
        console.log(`🤖 Vigthoria processStandardMessage: ${message}...`);
        
        try {
            // Update context manager mode
            if (this.contextManager) {
                this.contextManager.updateMode(mode.toUpperCase());
            }

            // For ASK and BUILD modes, use Ollama LLM with Vigthoria context
            if (mode.toLowerCase() === 'ask' || mode.toLowerCase() === 'build') {
                return await this.processVigthortiaMode(message, mode, analysis, options);
            }

            // Default fallback
            return {
                success: true,
                response: `Hello! I'm Vigthoria, your AI programming assistant. I understand you want me to help with: "${message}". Let me work on this ${analysis.complexity} ${mode} task.`,
                type: 'standard',
                source: 'vigthoria-basic',
                analysis: analysis
            };

        } catch (error) {
            console.error(`❌ Vigthoria processStandardMessage error: ${error}`);
            return this.fallbackToVigthoria(message, mode, error);
        }
    }

    /**
     * Process ASK/BUILD modes using Ollama LLM with Vigthoria context
     */
    /**
     * Check if a model is available for use
     * @param {Object} model - The model to check availability for
     * @returns {Promise<boolean>} - Whether the model is available
     */
    async checkModelAvailability(model) {
        try {
            if (!model || !model.name) {
                console.warn("⚠️ Invalid model provided for availability check");
                return false;
            }

            // For Ollama models, check if they are accessible
            if (model.name.includes("llama") || model.name.includes("ollama")) {
                try {
                    // Quick availability check - we will assume local models are available
                    return true;
                } catch (error) {
                    console.warn(`⚠️ Ollama model ${model.name} not available:`, error.message);
                    return false;
                }
            }

            // For other AI services, implement specific checks
            if (model.name.includes("openai") || model.name.includes("gpt")) {
                return true; // Simplified for now
            }

            if (model.name.includes("anthropic") || model.name.includes("claude")) {
                return true; // Simplified for now
            }

            // Default case - assume available
            console.log(`✅ Model ${model.name} availability check passed`);
            return true;

        } catch (error) {
            console.error(`❌ Error checking model availability for ${model?.name}:`, error);
            return false;
        }
    }

    async processVigthortiaMode(message, mode, analysis, options = {}) {
        const { subscription = 'basic', statusCallback } = options;
        
        console.log(`🤖 Building Vigthoria context for: ${message}...`);
        
        try {
            // Get subscription-appropriate model
            const model = this.getModelForSubscription(mode, subscription);
            
            // Get dynamic status message
            const statusInfo = this.getDynamicStatusMessage(mode, subscription, model);
            
            // Send status update if callback provided
            if (statusCallback) {
                statusCallback({
                    type: 'status',
                    data: {
                        processing: true,
                        message: statusInfo.processing,
                        model: statusInfo.model,
                        mode: mode.toUpperCase(),
                        subscription: statusInfo.subscription,
                        icon: statusInfo.icon
                    }
                });
            }

            // Build system prompt with Vigthoria context
            const systemPrompt = this.contextManager ? 
                this.contextManager.buildSystemPrompt(mode.toUpperCase(), message) : 
                this.getDefaultVigthortiaPrompt(mode, message);

            console.log(`📝 System prompt built, using model: ${model}...`);
            console.log(`💎 Subscription: ${subscription.toUpperCase()} | Mode: ${mode.toUpperCase()}`);

            // Call Ollama LLM with subscription-appropriate model
            const ollamaResponse = await this.callOllamaLLMOptimized(systemPrompt, model);

            if (!ollamaResponse || !ollamaResponse.response) {
                throw new Error('Invalid response from Ollama');
            }

            console.log('✅ Vigthoria response generated successfully');

            // Send completion status if callback provided
            if (statusCallback) {
                statusCallback({
                    type: 'complete',
                    data: {
                        processing: false,
                        model: statusInfo.model,
                        subscription: statusInfo.subscription
                    }
                });
            }

            return {
                success: true,
                response: ollamaResponse.response,
                type: mode.toLowerCase(),
                source: 'vigthoria-ollama',
                model: model,
                subscription: subscription,
                analysis: analysis
            };

        } catch (error) {
            console.error(`❌ Vigthoria mode error: ${error.message}`);
            
            // Send error status if callback provided
            if (statusCallback) {
                statusCallback({
                    type: 'error',
                    data: {
                        processing: false,
                        error: error.message
                    }
                });
            }
            
            return this.fallbackToVigthoria(message, mode, error);
        }
    }

    /**
     * Call Ollama LLM with proper error handling
     */
    async callOllamaLLM(prompt, model = 'llama3:8b-instruct-q4_0') {
        console.log(`🦙 Calling Ollama with model: ${model}`);
        
        try {
            const response = await fetch('http://localhost:11434/api/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model: model,
                    prompt: prompt,
                    stream: false,
                    options: {
                        temperature: 0.7,
                        top_p: 0.9,
                        max_tokens: 2000
                    }
                }),
                timeout: 60000
            });

            if (!response.ok) {
                throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
            }

            const result = await response.json();
            console.log(`✅ Ollama response received (${result.response?.length || 0} chars)`);
            
            return result;

        } catch (error) {
            console.error('❌ Ollama call failed:', error.message);
            throw new Error(`Ollama service unavailable: ${error.message}`);
        }
    }

    /**
     * 🧹 Model Lifecycle Management - Prevent Memory Issues
     */
    async unloadUnusedModels(currentModel) {
        try {
            console.log('🧹 Checking for unused models to unload...');
            
            // Get list of loaded models
            const response = await fetch('http://localhost:11434/api/ps');
            if (!response.ok) return;
            
            const data = await response.json();
            const loadedModels = data.models || [];
            
            // Unload models that aren't the current one and have been idle
            for (const modelInfo of loadedModels) {
                if (modelInfo.name !== currentModel && modelInfo.size_vram > 0) {
                    console.log(`🗑️ Unloading unused model: ${modelInfo.name}`);
                    await this.unloadModel(modelInfo.name);
                }
            }
        } catch (error) {
            console.warn('⚠️ Model cleanup failed:', error.message);
        }
    }

    async unloadModel(modelName) {
        try {
            const response = await fetch('http://localhost:11434/api/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    model: modelName,
                    keep_alive: 0  // Unload immediately
                })
            });
            
            if (response.ok) {
                console.log(`✅ Model unloaded: ${modelName}`);
            }
        } catch (error) {
            console.warn(`⚠️ Failed to unload model ${modelName}:`, error.message);
        }
    }

    /**
     * Optimized Ollama call with model management
     */
    async callOllamaLLMOptimized(prompt, model = 'llama3:8b-instruct-q4_0') {
        console.log(`🦙 Calling Ollama with model: ${model}`);
        
        try {
            // Unload unused models before loading new one
            await this.unloadUnusedModels(model);
            
            const response = await fetch('http://localhost:11434/api/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model: model,
                    prompt: prompt,
                    stream: false,
                    options: {
                        temperature: 0.7,
                        top_p: 0.9,
                        max_tokens: 2000
                    },
                    keep_alive: '5m'  // Keep model loaded for 5 minutes only
                }),
                timeout: 30000  // Reduced timeout for faster models
            });

            if (!response.ok) {
                throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
            }

            const result = await response.json();
            console.log(`✅ Ollama response received (${result.response?.length || 0} chars)`);
            
            return result;

        } catch (error) {
            console.error('❌ Ollama call failed:', error.message);
            // Fallback to smaller model on failure
            if (model !== 'phi3:mini') {
                console.log('🔄 Falling back to phi3:mini...');
                return await this.callOllamaLLMOptimized(prompt, 'phi3:mini');
            }
            throw new Error(`Ollama service unavailable: ${error.message}`);
        }
    }

    /**
     * Get appropriate model based on subscription tier and mode
     */
    getModelForSubscription(mode, subscription = 'basic') {
        const modelMatrix = {
            basic: {
                ask: 'phi3:mini',
                build: 'deepseek-coder:6.7b-instruct-q4_0'
            },
            premium: {
                ask: 'llama3:8b-instruct-q4_0',
                build: 'deepseek-coder-v2:latest'
            },
            enterprise: {
                ask: 'mixtral:8x7b-instruct-v0.1-q4_K_M',
                build: 'qwen2.5-coder:32b'
            },
            admin: {
                ask: 'mixtral:8x7b-instruct-v0.1-q4_K_M',
                build: 'qwen2.5-coder:32b'
            }
        };

        const tier = subscription.toLowerCase();
        const modeKey = mode.toLowerCase();
        
        return modelMatrix[tier]?.[modeKey] || modelMatrix.basic[modeKey] || 'llama3:8b-instruct-q4_0';
    }

    /**
     * Get dynamic status message based on mode, subscription, and model
     */
    getDynamicStatusMessage(mode, subscription, model) {
        const modeMessages = {
            ask: {
                processing: 'Vigthoria analyzing your question',
                model: model,
                icon: '🤖'
            },
            build: {
                processing: `Vigthoria generating code with ${model}`,
                model: model,
                icon: '🔨'
            },
            agent: {
                processing: 'Vigthoria_oAI1 agent processing',
                model: 'Vigthoria_oAI1',
                icon: '🤖'
            },
            operator: {
                processing: 'Vigthoria_GoA system operating',
                model: 'Vigthoria_GoA',
                icon: '⚙️'
            }
        };

        const modeKey = mode.toLowerCase();
        const messageData = modeMessages[modeKey] || modeMessages.ask;
        
        return {
            processing: messageData.processing,
            model: messageData.model,
            icon: messageData.icon,
            subscription: subscription.toUpperCase()
        };
    }

    /**
     * Get default Vigthoria prompt when context manager is unavailable
     */
    getDefaultVigthortiaPrompt(mode, message) {
        const identity = `I am Vigthoria, your AI Programming Assistant in the Vigthoria AI Chat - Advanced Code Intelligence environment.

My Capabilities:
• Advanced code analysis and generation
• Multi-AI model orchestration
• Real-time collaboration
• Intelligent debugging assistance
• Project context awareness
• Gamified development experience

Core Values:
• Precision in code quality
• Developer productivity enhancement
• Intelligent automation
• Seamless user experience`;

        const modeContext = mode.toLowerCase() === 'build' ? 
            `BUILD Mode: I'm optimized for code generation, project building, and development tasks. I can create files, write functions, build components, and help structure your projects with intelligent code suggestions.` :
            `ASK Mode: I'm ready to answer questions, explain concepts, provide quick help, and offer guidance on any development topics. Feel free to ask about code, technologies, best practices, or Vigthoria features.`;

        return `${identity}

${modeContext}

Please respond as Vigthoria with full awareness of your capabilities and the Vigthoria AI Chat application features. Provide helpful, intelligent assistance while maintaining your professional AI assistant personality.

User Message: ${message}

Vigthoria:`;
    }

    /**
     * Process AGENT mode - delegate to Vigthoria Agent Coder service
     */
    async processAgentMode(message, analysis) {
        console.log('🤖 Delegating to Vigthoria Agent Coder (port 8001)...');
        
        try {
            // Build context with Vigthoria identity
            const contextObj = this.contextManager ? 
                this.contextManager.buildSystemPrompt('AGENT', message) : 
                `AGENT Mode: ${message}`;

            const requestBody = {
                message: message,
                mode: 'AGENT',
                analysis: analysis,
                context: { 
                    prompt: contextObj,
                    mode: 'AGENT',
                    source: 'vigthoria-extension',
                    ...analysis 
                },
                timestamp: new Date().toISOString()
            };

            console.log('📨 Sending request to Agent service:', requestBody);

            try {
                const response = await fetch('http://localhost:8001/process', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'User-Agent': 'Vigthoria-AI-Chat/2.0.0'
                    },
                    body: JSON.stringify(requestBody),
                    timeout: 5000  // Reduced timeout for faster fallback
                });

                if (!response.ok) {
                    throw new Error(`Agent service responded with status: ${response.status}`);
                }

                const result = await response.json();
                console.log('✅ Agent service response received');

                return {
                    success: true,
                    response: result.response || result.message || 'Agent task completed',
                    type: 'agent',
                    source: 'vigthoria-agent-coder',
                    analysis: analysis,
                    serviceData: result
                };
            } catch (fetchError) {
                console.warn('⚠️ External Agent service unavailable, using internal fallback:', fetchError.message);
                
                // Fallback to internal agent processing
                const fallbackResponse = await this.processAgentFallback(message, analysis, context);
                return {
                    success: true,
                    response: fallbackResponse,
                    type: 'agent',
                    source: 'internal-fallback',
                    analysis: analysis,
                    fallback: true
                };
            }

        } catch (error) {
            console.error('❌ Agent service error:', error.message);
            return this.fallbackToVigthoria(message, 'AGENT', error);
        }
    }

    /**
     * Process OPERATOR mode - delegate to Vigthoria GoA service  
     */
    async processOperatorMode(message, analysis) {
        console.log('⚡ Delegating to Vigthoria GoA (port 5005)...');
        
        try {
            // Build context with Vigthoria identity
            const context = this.contextManager ? 
                this.contextManager.buildSystemPrompt('OPERATOR', message) : 
                `OPERATOR Mode: ${message}`;

            const requestBody = {
                message: message,
                mode: 'OPERATOR', 
                analysis: analysis,
                context: context,
                timestamp: new Date().toISOString()
            };

            console.log('📨 Sending request to GoA service:', requestBody);

            const response = await fetch('http://localhost:5005/api/operator', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'User-Agent': 'Vigthoria-AI-Chat/2.0.0'
                },
                body: JSON.stringify(requestBody),
                timeout: 30000
            });

            if (!response.ok) {
                throw new Error(`GoA service responded with status: ${response.status}`);
            }

            const result = await response.json();
            console.log('✅ GoA service response received');

            return {
                success: true,
                response: result.response || result.message || 'Operator task completed',
                type: 'operator',
                source: 'vigthoria-goa',
                analysis: analysis,
                serviceData: result
            };

        } catch (error) {
            console.error('❌ GoA service error:', error.message);
            return this.fallbackToVigthoria(message, 'OPERATOR', error);
        }
    }

    /**
     * Fallback to Vigthoria when external services are unavailable
     */
    fallbackToVigthoria(message, mode, error) {
        console.log(`🔄 Falling back to Vigthoria for ${mode} mode...`);
        
        const vigthortiaResponse = mode === 'AGENT' 
            ? `Hello! I'm Vigthoria, your AI development assistant. The Agent service is currently experiencing technical difficulties, but I'm here to help with your autonomous development tasks. I can still assist with code generation, project analysis, and development guidance. 

Your request: "${message}"

Please try again in a moment, or let me help you with a more specific development task. Error: ${error.message}`
            : `Hello! I'm Vigthoria, your AI system management assistant. The Operator service is currently experiencing technical difficulties, but I'm here to help with your system operations and management needs. I can assist with configuration, deployment guidance, and system administration tasks.

Your request: "${message}"

Please try again in a moment, or let me help you with a specific system management task. Error: ${error.message}`;

        return {
            success: true,
            response: vigthortiaResponse,
            type: mode.toLowerCase(),
            source: 'vigthoria-fallback',
            analysis: { complexity: 'medium', type: 'fallback' },
            error: error.message
        };
    }

    /**
     * Categorize message type
     */
    categorizeMessage(message, mode) {
        const categories = {
            'code_generation': ['create', 'generate', 'write', 'build'],
            'code_analysis': ['analyze', 'review', 'check', 'examine'],
            'debugging': ['debug', 'fix', 'error', 'bug', 'issue'],
            'explanation': ['explain', 'how', 'what', 'why', 'describe'],
            'optimization': ['optimize', 'improve', 'enhance', 'performance']
        };
        
        const lowerMessage = message.toLowerCase();
        for (const [category, keywords] of Object.entries(categories)) {
            if (keywords.some(keyword => lowerMessage.includes(keyword))) {
                return category;
            }
        }
        
        return mode === 'build' ? 'code_generation' : 'general';
    }

    /**
     * Extract key terms from message
     */
    extractKeywords(message) {
        const words = message.toLowerCase().split(/\s+/);
        const stopWords = ['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with'];
        return words.filter(word => word.length > 3 && !stopWords.includes(word)).slice(0, 10);
    }

    /**
     * Determine user intent
     */
    determineIntent(message, mode) {
        const intentMap = {
            'ask': 'seek_information',
            'build': 'create_solution',
            'agent': 'autonomous_execution',
            'operator': 'system_management'
        };
        
        return intentMap[mode] || 'general_assistance';
    }

    async processComplexTask(task) {
        console.log('🎯 Processing complex task with multi-AI orchestration...');
        
        // Analyze and decompose the task
        const decomposition = await this.decomposeTask(task);
        
        // Create orchestration plan
        const orchestrationPlan = await this.createOrchestrationPlan(decomposition);
        
        // Execute plan with AI coordination
        const results = await this.executeOrchestrationPlan(orchestrationPlan);
        
        // Synthesize final result
        const finalResult = await this.synthesizeResults(results, task);
        
        // Learn from execution
        await this.updateOrchestrationLearning(task, orchestrationPlan, results, finalResult);
        
        return finalResult;
    }

    async decomposeTask(task) {
        const analysis = {
            originalTask: task,
            complexity: this.assessTaskComplexity(task),
            requiredCapabilities: this.identifyRequiredCapabilities(task),
            dependencies: this.identifyTaskDependencies(task),
            estimatedDuration: this.estimateTaskDuration(task)
        };

        // Break down into subtasks
        const subtasks = [];
        
        if (this.requiresCreativity(task)) {
            subtasks.push({
                type: 'creativity',
                description: 'Generate creative solutions and approaches',
                priority: 1,
                dependencies: []
            });
        }

        if (this.requiresArchitecture(task)) {
            subtasks.push({
                type: 'architecture',
                description: 'Design system architecture and structure',
                priority: 1,
                dependencies: []
            });
        }

        if (this.requiresCoding(task)) {
            subtasks.push({
                type: 'optimization',
                description: 'Generate and optimize code implementation',
                priority: 2,
                dependencies: ['architecture', 'creativity']
            });
        }

        if (this.requiresSecurity(task)) {
            subtasks.push({
                type: 'security',
                description: 'Analyze and enhance security aspects',
                priority: 2,
                dependencies: ['architecture', 'optimization']
            });
        }

        if (this.requiresTesting(task)) {
            subtasks.push({
                type: 'testing',
                description: 'Generate comprehensive tests',
                priority: 3,
                dependencies: ['optimization']
            });
        }

        if (this.requiresDocumentation(task)) {
            subtasks.push({
                type: 'documentation',
                description: 'Create documentation and explanations',
                priority: 3,
                dependencies: ['optimization', 'testing']
            });
        }

        return {
            analysis,
            subtasks,
            executionOrder: this.calculateExecutionOrder(this.validateTaskStructure(subtasks))
        };
    }

    calculateExecutionOrder(subtasks) {
        // Simple dependency-based execution order
        const ordered = [];
        const remaining = [...subtasks];
        
        // Add subtasks with no dependencies first
        while (remaining.length > 0) {
            const readyTasks = remaining.filter(task => {
                if (!task.dependencies || task.dependencies.length === 0) return true;
                return task.dependencies.every(dep => 
                    ordered.some(completed => completed.id === dep)
                );
            });
            
            if (readyTasks.length === 0) {
                // If no tasks are ready, add remaining tasks in order to prevent deadlock
                ordered.push(...remaining);
                break;
            }
            
            ordered.push(...readyTasks);
            readyTasks.forEach(task => {
                const index = remaining.indexOf(task);
                remaining.splice(index, 1);
            });
        }
        
        return ordered.map(task => task.id || task.name || 'unnamed-task');
    }

    validateTaskStructure(subtasks) {
        return subtasks.map((task, index) => ({
            id: task.id || ('task-' + index),
            name: task.name || task.description || ('Task ' + (index + 1)),
            description: task.description || task.name || 'Automated task',
            priority: task.priority || 'medium',
            estimatedTime: task.estimatedTime || '5-10 minutes',
            dependencies: task.dependencies || [],
            assignedService: task.assignedService || 'general'
        }));
    }

    async createOrchestrationPlan(decomposition) {
        const plan = {
            phases: [],
            totalEstimatedTime: 0,
            resourceRequirements: new Map(),
            riskAssessment: this.assessOrchestrationRisk(decomposition)
        };

        // Group subtasks into execution phases
        const phases = this.groupSubtasksIntoPhases(decomposition.subtasks);
        
        for (const [phaseIndex, phaseTasks] of phases.entries()) {
            const phase = {
                id: `phase_${phaseIndex + 1}`,
                name: this.generatePhaseName(phaseTasks),
                tasks: [],
                parallelExecution: this.canExecuteInParallel(phaseTasks),
                estimatedDuration: 0
            };

            for (const subtask of phaseTasks) {
                const aiSelection = await this.selectOptimalAI(subtask);
                const taskPlan = {
                    subtask,
                    selectedAI: aiSelection.primary,
                    backupAIs: aiSelection.alternatives,
                    estimatedDuration: aiSelection.estimatedDuration,
                    qualityChecks: this.defineQualityChecks(subtask),
                    fallbackStrategy: this.defineFallbackStrategy(subtask, aiSelection)
                };
                
                phase.tasks.push(taskPlan);
                phase.estimatedDuration = Math.max(phase.estimatedDuration, taskPlan.estimatedDuration);
            }

            plan.phases.push(phase);
            plan.totalEstimatedTime += phase.estimatedDuration;
        }

        return plan;
    }

    async executeOrchestrationPlan(plan) {
        const results = {
            phases: [],
            totalExecutionTime: 0,
            successRate: 0,
            qualityMetrics: new Map()
        };

        const startTime = Date.now();

        for (const phase of plan.phases) {
            console.log(`🚀 Executing ${phase.name}...`);
            
            const phaseStartTime = Date.now();
            const phaseResults = await this.executePhase(phase);
            const phaseEndTime = Date.now();

            phaseResults.executionTime = phaseEndTime - phaseStartTime;
            results.phases.push(phaseResults);

            // Quality gate check
            if (!this.passesQualityGate(phaseResults)) {
                await this.handleQualityGateFailure(phase, phaseResults);
            }
        }

        results.totalExecutionTime = Date.now() - startTime;
        results.successRate = this.calculateSuccessRate(results.phases);

        return results;
    }

    calculateSuccessRate(phases) {
        if (!phases || phases.length === 0) return 0;
        
        let totalTasks = 0;
        let successfulTasks = 0;
        
        phases.forEach(phase => {
            if (phase.tasks) {
                totalTasks += phase.tasks.length;
                successfulTasks += phase.tasks.filter(task => 
                    task.status === "completed" || task.success === true
                ).length;
            }
        });
        
        return totalTasks > 0 ? (successfulTasks / totalTasks) * 100 : 0;
    }

    async executePhase(phase) {
        const phaseResults = {
            phaseId: phase.id,
            phaseName: phase.name,
            taskResults: [],
            overallSuccess: true,
            qualityScore: 0
        };

        if (phase.parallelExecution) {
            // Execute tasks in parallel
            const taskPromises = phase.tasks.map(task => this.executeTask(task));
            const taskResults = await Promise.allSettled(taskPromises);
            
            for (const [index, result] of taskResults.entries()) {
                if (result.status === 'fulfilled') {
                    phaseResults.taskResults.push(result.value);
                } else {
                    // Handle failed task with fallback
                    const fallbackResult = await this.executeFallbackStrategy(phase.tasks[index], result.reason);
                    phaseResults.taskResults.push(fallbackResult);
                    phaseResults.overallSuccess = false;
                }
            }
        } else {
            // Execute tasks sequentially
            for (const task of phase.tasks) {
                try {
                    const taskResult = await this.executeTask(task);
                    phaseResults.taskResults.push(taskResult);
                } catch (error) {
                    const fallbackResult = await this.executeFallbackStrategy(task, error);
                    phaseResults.taskResults.push(fallbackResult);
                    phaseResults.overallSuccess = false;
                }
            }
        }

        phaseResults.qualityScore = this.calculatePhaseQualityScore(phaseResults.taskResults);
        return phaseResults;
    }

    async executeTask(taskPlan) {
        const { subtask, selectedAI, qualityChecks } = taskPlan;
        
        // Execute the task with selected AI
        const aiResult = await this.callAI(selectedAI, subtask);
        
        // Run quality checks
        const qualityResults = await this.runQualityChecks(aiResult, qualityChecks);
        
        // If quality is insufficient, try with backup AI
        if (!qualityResults.passed && taskPlan.backupAIs.length > 0) {
            console.log(`⚠️ Quality check failed, trying backup AI...`);
            const backupAI = taskPlan.backupAIs[0];
            const backupResult = await this.callAI(backupAI, subtask);
            const backupQuality = await this.runQualityChecks(backupResult, qualityChecks);
            
            if (backupQuality.passed || backupQuality.score > qualityResults.score) {
                return {
                    subtask,
                    result: backupResult,
                    aiUsed: backupAI,
                    qualityScore: backupQuality.score,
                    fallbackUsed: true
                };
            }
        }

        return {
            subtask,
            result: aiResult,
            aiUsed: selectedAI,
            qualityScore: qualityResults.score,
            fallbackUsed: false
        };
    }

    async synthesizeResults(results, originalTask) {
        console.log('🎯 Synthesizing multi-AI results...');
        
        // Collect all task results
        const allTaskResults = results.phases.flatMap(phase => phase.taskResults);
        
        // Group results by type
        const resultsByType = this.groupResultsByType(allTaskResults);
        
        // Create synthesis plan
        const synthesisAI = await this.selectSynthesisAI(originalTask, resultsByType);
        
        // Generate final synthesized result
        const synthesizedResult = await this.callAI(synthesisAI, {
            type: 'synthesis',
            originalTask,
            results: resultsByType,
            context: 'Combine and synthesize the following AI-generated results into a cohesive final solution'
        });

        return {
            originalTask,
            synthesizedResult,
            componentResults: resultsByType,
            orchestrationMetrics: {
                totalAIsUsed: this.countUniqueAIs(allTaskResults),
                totalExecutionTime: results.totalExecutionTime,
                overallQualityScore: this.calculateOverallQuality(allTaskResults),
                successRate: results.successRate
            },
            improvements: this.identifyImprovements(results, synthesizedResult),
            nextSteps: this.generateNextSteps(originalTask, synthesizedResult)
        };
    }

    groupResultsByType(taskResults) {
        const grouped = {};
        
        taskResults.forEach(result => {
            const type = result.type || result.subtask?.type || 'general';
            if (!grouped[type]) {
                grouped[type] = [];
            }
            grouped[type].push(result);
        });
        
        return grouped;
    }

    async selectOptimalAI(subtask) {
        const aiCategory = this.aiModels.get(subtask.type);
        if (!aiCategory) {
            throw new Error(`No AI category found for task type: ${subtask.type}`);
        }

        const scoredModels = await Promise.all(
            aiCategory.models.map(async (model) => ({
                model,
                score: await this.scoreModelForTask(model, subtask),
                availability: await this.checkModelAvailability(model),
                estimatedDuration: this.estimateModelDuration(model, subtask)
            }))
        );

        const availableModels = scoredModels.filter(m => m.availability);
        availableModels.sort((a, b) => b.score - a.score);

        return {
            primary: availableModels[0].model,
            alternatives: availableModels.slice(1).map(m => m.model),
            estimatedDuration: availableModels[0].estimatedDuration
        };
    }

    async selectSynthesisAI(originalTask, resultsByType) {
        // Select the best AI for synthesizing multi-AI results
        console.log('🤖 Selecting synthesis AI...');
        
        // Priority for synthesis: GPT-4 > Claude > GPT-3.5 > Gemini
        const synthesisPreference = ['gpt-4', 'claude-3-opus', 'claude-3-sonnet', 'gpt-3.5-turbo', 'gemini-pro'];
        
        // Check availability and select best option
        for (const modelName of synthesisPreference) {
            const isAvailable = await this.checkModelAvailability({ name: modelName });
            if (isAvailable) {
                console.log(`✅ Selected ${modelName} for synthesis`);
                return { 
                    name: modelName, 
                    type: 'synthesis',
                    capabilities: ['reasoning', 'analysis', 'synthesis']
                };
            }
        }
        
        // Fallback to first available model
        const fallbackModel = { 
            name: 'gpt-3.5-turbo', 
            type: 'synthesis',
            capabilities: ['reasoning', 'analysis'] 
        };
        console.log(`⚠️ Using fallback model for synthesis: ${fallbackModel.name}`);
        return fallbackModel;
    }

    // Helper methods for task analysis

    // Task analysis methods
    assessTaskComplexity(task) {
        let complexityScore = 0;
        
        // Check task description complexity
        const description = task.description || task.message || "";
        if (description.length > 200) complexityScore += 2;
        if (description.length > 500) complexityScore += 3;
        
        // Check for complex keywords
        const complexKeywords = ["algorithm", "architecture", "integration", "optimization", "machine learning", "database", "security", "performance"];
        complexityScore += complexKeywords.filter(keyword => description.toLowerCase().includes(keyword)).length;
        
        // Check for multiple requirements
        if (task.requirements && task.requirements.length > 3) complexityScore += 2;
        if (task.requirements && task.requirements.length > 7) complexityScore += 3;
        
        // Return complexity level
        if (complexityScore <= 2) return "low";
        if (complexityScore <= 6) return "medium";
        if (complexityScore <= 10) return "high";
        return "extreme";
    }
    
    identifyRequiredCapabilities(task) {
        const capabilities = [];
        const description = (task.description || task.message || "").toLowerCase();
        
        // Code-related capabilities
        if (description.includes("code") || description.includes("program")) capabilities.push("coding");
        if (description.includes("test") || description.includes("debug")) capabilities.push("testing");
        if (description.includes("document") || description.includes("explain")) capabilities.push("documentation");
        if (description.includes("review") || description.includes("analyze")) capabilities.push("analysis");
        if (description.includes("deploy") || description.includes("build")) capabilities.push("deployment");
        if (description.includes("design") || description.includes("architect")) capabilities.push("architecture");
        if (description.includes("secure") || description.includes("auth")) capabilities.push("security");
        if (description.includes("optimize") || description.includes("performance")) capabilities.push("optimization");
        
        return capabilities.length > 0 ? capabilities : ["general"];
    }
    
    identifyTaskDependencies(task) {
        const dependencies = [];
        const description = (task.description || task.message || "").toLowerCase();
        
        // File dependencies
        if (description.includes("file") || description.includes("read") || description.includes("write")) {
            dependencies.push({ type: "file-system", description: "File system access required" });
        }
        
        // Network dependencies  
        if (description.includes("api") || description.includes("http") || description.includes("request")) {
            dependencies.push({ type: "network", description: "Network access required" });
        }
        
        // Database dependencies
        if (description.includes("database") || description.includes("sql") || description.includes("query")) {
            dependencies.push({ type: "database", description: "Database access required" });
        }
        
        // External tool dependencies
        if (description.includes("git") || description.includes("npm") || description.includes("docker")) {
            dependencies.push({ type: "tools", description: "External tools required" });
        }
        
        return dependencies;
    }
    
    estimateTaskDuration(task) {
        const complexity = this.assessTaskComplexity(task);
        const capabilities = this.identifyRequiredCapabilities(task);
        const dependencies = this.identifyTaskDependencies(task);
        
        let baseMinutes = 5; // Base task time
        
        // Complexity multiplier
        switch(complexity) {
            case "low": baseMinutes *= 1; break;
            case "medium": baseMinutes *= 3; break;
            case "high": baseMinutes *= 7; break;
            case "extreme": baseMinutes *= 15; break;
        }
        
        // Capability multiplier
        baseMinutes += capabilities.length * 2;
        
        // Dependency multiplier
        baseMinutes += dependencies.length * 5;
        
        return {
            estimated: baseMinutes,
            unit: "minutes",
            confidence: dependencies.length > 2 ? "low" : complexity === "extreme" ? "medium" : "high"
        };
    }

    requiresCreativity(task) {
        const creativityKeywords = ['innovative', 'creative', 'brainstorm', 'design', 'novel', 'unique'];
        return creativityKeywords.some(keyword => 
            task.description?.toLowerCase().includes(keyword) || 
            task.requirements?.some(req => req.toLowerCase().includes(keyword))
        );
    }

    requiresArchitecture(task) {
        const architectureKeywords = ['architecture', 'design', 'structure', 'system', 'scalable', 'framework'];
        return architectureKeywords.some(keyword => 
            task.description?.toLowerCase().includes(keyword)
        );
    }

    requiresCoding(task) {
        const codingKeywords = ['code', 'implement', 'develop', 'program', 'function', 'algorithm'];
        return codingKeywords.some(keyword => 
            task.description?.toLowerCase().includes(keyword)
        );
    }

    requiresSecurity(task) {
        const securityKeywords = ['security', 'secure', 'vulnerability', 'authentication', 'authorization', 'encryption'];
        return securityKeywords.some(keyword => 
            task.description?.toLowerCase().includes(keyword)
        );
    }

    requiresTesting(task) {
        const testingKeywords = ['test', 'testing', 'quality', 'validation', 'coverage'];
        return testingKeywords.some(keyword => 
            task.description?.toLowerCase().includes(keyword)
        );
    }

    requiresDocumentation(task) {
        const docKeywords = ['document', 'documentation', 'explain', 'comment', 'readme'];
        return docKeywords.some(keyword => 
            task.description?.toLowerCase().includes(keyword)
        );
    }

    assessOrchestrationRisk(decomposition) {
        const riskFactors = {
            complexityRisk: 0,
            dependencyRisk: 0,
            resourceRisk: 0,
            timeRisk: 0
        };

        // Assess complexity risk
        const highComplexityTasks = decomposition.subtasks.filter(task => 
            this.assessTaskComplexity(task) === 'high'
        ).length;
        riskFactors.complexityRisk = Math.min(highComplexityTasks / decomposition.subtasks.length, 1);

        // Assess dependency risk
        const totalDependencies = decomposition.subtasks.reduce((acc, task) => 
            acc + (task.dependencies?.length || 0), 0
        );
        riskFactors.dependencyRisk = Math.min(totalDependencies / (decomposition.subtasks.length * 2), 1);

        // Assess resource risk
        const uniqueServices = new Set(decomposition.subtasks.map(task => 
            task.assignedService || 'general'
        )).size;
        riskFactors.resourceRisk = Math.min(uniqueServices / 4, 1); // Assuming 4 max services

        // Assess time risk
        const totalEstimatedTime = decomposition.subtasks.reduce((acc, task) => 
            acc + this.estimateTaskDuration(task), 0
        );
        riskFactors.timeRisk = Math.min(totalEstimatedTime / 3600, 1); // Risk increases with time > 1 hour

        // Calculate overall risk score
        const overallRisk = Object.values(riskFactors).reduce((acc, risk) => acc + risk, 0) / 4;

        return {
            level: overallRisk < 0.3 ? 'low' : overallRisk < 0.7 ? 'medium' : 'high',
            score: overallRisk,
            factors: riskFactors,
            recommendations: this.generateRiskRecommendations(riskFactors)
        };
    }

    generateRiskRecommendations(riskFactors) {
        const recommendations = [];

        if (riskFactors.complexityRisk > 0.5) {
            recommendations.push('Consider breaking down complex tasks further');
        }
        if (riskFactors.dependencyRisk > 0.5) {
            recommendations.push('Review task dependencies to minimize bottlenecks');
        }
        if (riskFactors.resourceRisk > 0.5) {
            recommendations.push('Consider load balancing across available services');
        }
        if (riskFactors.timeRisk > 0.5) {
            recommendations.push('Consider parallel execution where possible');
        }

        return recommendations;
    }

    groupSubtasksIntoPhases(subtasks) {
        const phases = [];
        const processedTasks = new Set();
        const executionOrder = this.calculateExecutionOrder(subtasks);

        // Group tasks into phases based on dependencies
        let currentPhase = [];
        
        for (const task of executionOrder) {
            const canRunInCurrentPhase = !task.dependencies || 
                task.dependencies.every(dep => processedTasks.has(dep));

            if (canRunInCurrentPhase && currentPhase.length === 0) {
                currentPhase.push(task);
            } else if (canRunInCurrentPhase && currentPhase.length > 0) {
                // Check if this task can run in parallel with current phase
                const hasConflicts = currentPhase.some(phaseTask => 
                    phaseTask.dependencies?.includes(task.id) || 
                    task.dependencies?.includes(phaseTask.id)
                );
                
                if (!hasConflicts) {
                    currentPhase.push(task);
                } else {
                    // Start new phase
                    phases.push([...currentPhase]);
                    currentPhase = [task];
                }
            } else {
                // Dependencies not met, start new phase
                if (currentPhase.length > 0) {
                    phases.push([...currentPhase]);
                    currentPhase = [];
                }
                currentPhase.push(task);
            }
            
            processedTasks.add(task.id);
        }

        // Add final phase if not empty
        if (currentPhase.length > 0) {
            phases.push(currentPhase);
        }

        return phases;
    }

    generatePhaseName(phaseTasks) {
        if (phaseTasks.length === 1) {
            return phaseTasks[0].type.charAt(0).toUpperCase() + 
                   phaseTasks[0].type.slice(1) + ' Phase';
        }

        // Find the most common task type in this phase
        const taskTypes = phaseTasks.map(task => task.type);
        const typeCount = taskTypes.reduce((acc, type) => {
            acc[type] = (acc[type] || 0) + 1;
            return acc;
        }, {});

        const dominantType = Object.keys(typeCount).reduce((a, b) => 
            typeCount[a] > typeCount[b] ? a : b
        );

        if (typeCount[dominantType] === taskTypes.length) {
            return dominantType.charAt(0).toUpperCase() + dominantType.slice(1) + ' Phase';
        }

        return `Mixed ${dominantType.charAt(0).toUpperCase() + dominantType.slice(1)} Phase`;
    }

    /**
     * Process ASK and BUILD modes with Vigthoria context and optimized models
     */
    /**
     * Check if a model is available for use
     * @param {Object} model - The model to check availability for
     * @returns {Promise<boolean>} - Whether the model is available
     */
    async checkModelAvailability(model) {
        try {
            if (!model || !model.name) {
                console.warn("⚠️ Invalid model provided for availability check");
                return false;
            }

            // For Ollama models, check if they are accessible
            if (model.name.includes("llama") || model.name.includes("ollama")) {
                try {
                    // Quick availability check - we will assume local models are available
                    return true;
                } catch (error) {
                    console.warn(`⚠️ Ollama model ${model.name} not available:`, error.message);
                    return false;
                }
            }

            // For other AI services, implement specific checks
            if (model.name.includes("openai") || model.name.includes("gpt")) {
                return true; // Simplified for now
            }

            if (model.name.includes("anthropic") || model.name.includes("claude")) {
                return true; // Simplified for now
            }

            // Default case - assume available
            console.log(`✅ Model ${model.name} availability check passed`);
            return true;

        } catch (error) {
            console.error(`❌ Error checking model availability for ${model?.name}:`, error);
            return false;
        }
    }

    async processVigthortiaMode(message, mode, analysis, options = {}) {
        console.log(`🎯 Vigthoria ${mode.toUpperCase()} Mode processing: ${message}`);
        
        try {
            // Get subscription-based model for the mode
            const subscription = options.subscription || 'BASIC';
            const selectedModel = this.getModelForMode(mode, subscription);
            
            // Build Vigthoria-specific context
            const vigthortiaContext = this.buildVigthortiaContext(message, mode, analysis);
            
            // Use optimized Ollama call with model management
            const response = await this.callOllamaLLMOptimized(vigthortiaContext, selectedModel);
            
            return {
                success: true,
                response: response,
                type: mode,
                source: 'vigthoria-ollama',
                model: selectedModel,
                analysis: analysis,
                metadata: {
                    subscription: subscription,
                    timestamp: new Date().toISOString()
                }
            };
            
        } catch (error) {
            console.error(`❌ Vigthoria ${mode} mode error:`, error);
            return this.fallbackToVigthoria(message, mode, error);
        }
    }

    /**
     * Get optimized model for specific mode and subscription
     */
    getModelForMode(mode, subscription) {
        const subscriptionModels = {
            BASIC: {
                ask: 'llama3:8b-instruct-q4_0',
                build: 'deepseek-coder:6.7b-instruct-q4_0'
            },
            PROFESSIONAL: {
                ask: 'llama3:8b-instruct-q4_0', 
                build: 'deepseek-coder-v2:latest'
            },
            ENTERPRISE: {
                ask: 'mixtral:8x7b-instruct-v0.1-q4_K_M',
                build: 'qwen2.5-coder:32b'
            }
        };

        return subscriptionModels[subscription]?.[mode] || 'llama3:8b-instruct-q4_0';
    }

    /**
     * Build Vigthoria-specific context for different modes
     */
    buildVigthortiaContext(message, mode, analysis) {
        const baseContext = `You are Vigthoria, an advanced AI programming assistant integrated into VS Code. You have deep knowledge of the Vigthoria AI Chat extension and its capabilities.`;
        
        const modeContexts = {
            ask: `${baseContext}\n\nASK Mode: You excel at answering questions about programming, explaining concepts, debugging issues, and providing guidance. Be helpful, accurate, and educational.`,
            build: `${baseContext}\n\nBUILD Mode: You are an expert developer capable of creating, building, fixing, and editing code. Generate high-quality code solutions, provide implementation guidance, and help with project architecture.`
        };

        const contextPrompt = modeContexts[mode] || modeContexts.ask;
        
        return `${contextPrompt}\n\nUser Request: ${message}\n\nPlease provide a comprehensive and helpful response.`;
    }

    /**
     * Process agent mode with internal fallback
     */
    async processAgentFallback(message, analysis, context) {
        console.log('🤖 Processing agent request with internal fallback...');
        
        try {
            // Use local Ollama for agent-like responses
            const prompt = `You are Vigthoria Agent, an autonomous AI developer. 
User Request: ${message}

Provide a comprehensive analysis and action plan as an autonomous agent would:
- Analyze the request thoroughly
- Suggest specific implementation steps
- Provide code examples if relevant
- Outline testing strategies
- Give deployment recommendations`;

            const response = await this.callLocalOllama(prompt, {
                model: 'llama3:8b-instruct-q4_0',
                mode: 'agent',
                ...context
            });

            return response.content || `🤖 **Vigthoria Agent Analysis**

I've analyzed your request: "${message}"

**Recommended Actions:**
1. Further analysis of requirements
2. Implementation planning and design
3. Code development with best practices
4. Testing and validation
5. Deployment and monitoring

While my external agent services are temporarily unavailable, I can still provide autonomous assistance with your development tasks.`;
            
        } catch (error) {
            console.error('Agent fallback error:', error);
            return `🤖 **Vigthoria Agent**

I understand you need: "${message}"

I'm currently operating in fallback mode but ready to assist with your development needs. Please provide more specific details about your requirements so I can help effectively.`;
        }
    }

    /**
     * Fallback response when Vigthoria processing fails
     */
    fallbackToVigthoria(message, mode, error) {
        console.log(`🛡️ Vigthoria fallback for ${mode} mode`);
        
        const fallbackResponses = {
            ask: `Hello! I'm Vigthoria, your AI programming assistant. I understand you're asking about: "${message}". While I'm experiencing some technical difficulties connecting to my advanced processing systems, I'm still here to help with your programming questions and development needs.`,
            build: `Hello! I'm Vigthoria, your AI development assistant. I see you want to build or create: "${message}". Although I'm having some connectivity issues with my specialized coding models, I can still assist with code generation, project planning, and development guidance. Please let me know more details about what you'd like to create.`
        };

        return {
            success: true,
            response: fallbackResponses[mode] || fallbackResponses.ask,
            type: mode,
            source: 'vigthoria-fallback',
            error: error?.message,
            metadata: {
                fallback: true,
                timestamp: new Date().toISOString()
            }
        };
    }
}

module.exports = { MultiAIOrchestrator };
