/**
 * 🏗️ VIGTHORIA MODULAR ARCHITECTURE MANAGER
 * Orchestrates the modular decomposition of the main extension system
 */

const path = require('path');
const EventEmitter = require('events');

class ModularArchitectureManager extends EventEmitter {
    constructor() {
        super();
        
        this.modules = new Map();
        this.dependencies = new Map();
        this.loadOrder = [];
        this.moduleStates = new Map();
        
        this.initializeModuleStructure();
    }

    initializeModuleStructure() {
        // Define the modular architecture structure
        this.moduleDefinitions = {
            // Core System Modules
            'core/activation-manager': {
                path: './modules/core/activation-manager.js',
                dependencies: ['core/config-manager'],
                priority: 1,
                description: 'Handles VS Code extension activation and deactivation'
            },
            
            'core/config-manager': {
                path: './modules/core/config-manager.js',
                dependencies: [],
                priority: 0,
                description: 'Manages configuration settings and user preferences'
            },
            
            'core/command-registry': {
                path: './modules/core/command-registry.js',
                dependencies: ['core/config-manager'],
                priority: 1,
                description: 'Registers and manages VS Code commands'
            },
            
            'core/webview-manager': {
                path: './modules/core/webview-manager.js',
                dependencies: ['core/config-manager', 'ui/sidebar-provider'],
                priority: 2,
                description: 'Manages webview creation and communication'
            },
            
            // AI System Modules
            'ai/orchestrator': {
                path: './modules/ai/orchestrator.js',
                dependencies: ['core/config-manager', 'ai/providers/registry'],
                priority: 3,
                description: 'Main AI orchestration system'
            },
            
            'ai/providers/registry': {
                path: './modules/ai/providers/registry.js',
                dependencies: ['core/config-manager'],
                priority: 2,
                description: 'AI provider registration and management'
            },
            
            'ai/providers/ollama': {
                path: './modules/ai/providers/ollama.js',
                dependencies: ['ai/providers/registry'],
                priority: 3,
                description: 'Ollama AI provider implementation'
            },
            
            'ai/providers/huggingface': {
                path: './modules/ai/providers/huggingface.js',
                dependencies: ['ai/providers/registry'],
                priority: 3,
                description: 'HuggingFace AI provider implementation'
            },
            
            'ai/providers/vigthoria-oai1': {
                path: './modules/ai/providers/vigthoria-oai1.js',
                dependencies: ['ai/providers/registry'],
                priority: 3,
                description: 'Vigthoria oAI1 agent provider'
            },
            
            // Mode System Modules
            'modes/ask-mode': {
                path: './modules/modes/ask-mode.js',
                dependencies: ['ai/orchestrator', 'ui/chat-interface'],
                priority: 4,
                description: 'ASK mode implementation'
            },
            
            'modes/build-mode': {
                path: './modules/modes/build-mode.js',
                dependencies: ['ai/orchestrator', 'workspace/file-manager'],
                priority: 4,
                description: 'BUILD mode implementation'
            },
            
            'modes/agent-mode': {
                path: './modules/modes/agent-mode.js',
                dependencies: ['ai/orchestrator', 'agents/sub-agent-manager'],
                priority: 4,
                description: 'AGENT mode implementation'
            },
            
            'modes/operator-mode': {
                path: './modules/modes/operator-mode.js',
                dependencies: ['ai/orchestrator', 'workspace/context-manager'],
                priority: 4,
                description: 'OPERATOR mode implementation'
            },
            
            // Agent System Modules
            'agents/sub-agent-manager': {
                path: './modules/agents/sub-agent-manager.js',
                dependencies: ['ai/orchestrator'],
                priority: 3,
                description: 'Sub-agent creation and management'
            },
            
            'agents/capabilities-engine': {
                path: './modules/agents/capabilities-engine.js',
                dependencies: ['agents/sub-agent-manager'],
                priority: 4,
                description: 'Agent capabilities and enhancement system'
            },
            
            // UI System Modules
            'ui/sidebar-provider': {
                path: './modules/ui/sidebar-provider.js',
                dependencies: ['core/config-manager'],
                priority: 2,
                description: 'VS Code sidebar tree view provider'
            },
            
            'ui/chat-interface': {
                path: './modules/ui/chat-interface.js',
                dependencies: ['core/webview-manager'],
                priority: 3,
                description: 'Chat interface implementation'
            },
            
            'ui/status-bar': {
                path: './modules/ui/status-bar.js',
                dependencies: ['core/config-manager'],
                priority: 2,
                description: 'Status bar indicators and controls'
            },
            
            // Workspace System Modules
            'workspace/file-manager': {
                path: './modules/workspace/file-manager.js',
                dependencies: ['core/config-manager'],
                priority: 2,
                description: 'File system operations and management'
            },
            
            'workspace/context-manager': {
                path: './modules/workspace/context-manager.js',
                dependencies: ['workspace/file-manager'],
                priority: 3,
                description: 'Workspace context analysis and management'
            },
            
            'workspace/project-intelligence': {
                path: './modules/workspace/project-intelligence.js',
                dependencies: ['workspace/context-manager'],
                priority: 4,
                description: 'Project structure analysis and intelligence'
            },
            
            // Security System Modules
            'security/sandbox-manager': {
                path: './modules/security/sandbox-manager.js',
                dependencies: ['core/config-manager'],
                priority: 2,
                description: 'Security sandbox implementation'
            },
            
            'security/auth-manager': {
                path: './modules/security/auth-manager.js',
                dependencies: ['core/config-manager'],
                priority: 1,
                description: 'Authentication and authorization'
            },
            
            // Performance System Modules
            'performance/optimizer': {
                path: './modules/performance/optimizer.js',
                dependencies: ['core/config-manager'],
                priority: 2,
                description: 'Performance optimization and monitoring'
            },
            
            'performance/memory-manager': {
                path: './modules/performance/memory-manager.js',
                dependencies: ['performance/optimizer'],
                priority: 3,
                description: 'Memory management and cleanup'
            },
            
            // Utility Modules
            'utils/logger': {
                path: './modules/utils/logger.js',
                dependencies: [],
                priority: 0,
                description: 'Centralized logging system'
            },
            
            'utils/metrics-collector': {
                path: './modules/utils/metrics-collector.js',
                dependencies: ['utils/logger'],
                priority: 1,
                description: 'Metrics collection and reporting'
            },
            
            'utils/event-bus': {
                path: './modules/utils/event-bus.js',
                dependencies: [],
                priority: 0,
                description: 'Inter-module communication event bus'
            }
        };

        console.log(`🏗️ Modular architecture defined with ${Object.keys(this.moduleDefinitions).length} modules`);
    }

    async loadAllModules() {
        try {
            // Calculate load order based on dependencies and priorities
            this.calculateLoadOrder();
            
            console.log(`📦 Loading modules in calculated order...`);
            
            // Load modules in order
            for (const moduleId of this.loadOrder) {
                await this.loadModule(moduleId);
            }
            
            console.log(`✅ All modules loaded successfully`);
            this.emit('allModulesLoaded');
            
        } catch (error) {
            console.error(`❌ Failed to load modules:`, error);
            this.emit('moduleLoadError', error);
            throw error;
        }
    }

    calculateLoadOrder() {
        const visited = new Set();
        const visiting = new Set();
        const loadOrder = [];
        
        const visit = (moduleId) => {
            if (visited.has(moduleId)) return;
            if (visiting.has(moduleId)) {
                throw new Error(`Circular dependency detected involving module: ${moduleId}`);
            }
            
            visiting.add(moduleId);
            
            const moduleDef = this.moduleDefinitions[moduleId];
            if (!moduleDef) {
                throw new Error(`Module definition not found: ${moduleId}`);
            }
            
            // Visit dependencies first
            for (const dependency of moduleDef.dependencies) {
                visit(dependency);
            }
            
            visiting.delete(moduleId);
            visited.add(moduleId);
            loadOrder.push(moduleId);
        };
        
        // Sort modules by priority first, then resolve dependencies
        const moduleIds = Object.keys(this.moduleDefinitions)
            .sort((a, b) => {
                const priorityA = this.moduleDefinitions[a].priority;
                const priorityB = this.moduleDefinitions[b].priority;
                return priorityA - priorityB;
            });
        
        for (const moduleId of moduleIds) {
            visit(moduleId);
        }
        
        this.loadOrder = loadOrder;
        console.log(`📋 Module load order calculated: ${loadOrder.length} modules`);
    }

    async loadModule(moduleId) {
        const moduleDef = this.moduleDefinitions[moduleId];
        if (!moduleDef) {
            throw new Error(`Module definition not found: ${moduleId}`);
        }
        
        if (this.modules.has(moduleId)) {
            console.log(`⚠️ Module ${moduleId} already loaded, skipping`);
            return this.modules.get(moduleId);
        }
        
        console.log(`🔄 Loading module: ${moduleId}`);
        
        try {
            // Check if dependencies are loaded
            for (const dependency of moduleDef.dependencies) {
                if (!this.modules.has(dependency)) {
                    throw new Error(`Dependency ${dependency} not loaded for module ${moduleId}`);
                }
            }
            
            // Create module instance
            const moduleInstance = await this.createModuleInstance(moduleId, moduleDef);
            
            // Register module
            this.modules.set(moduleId, moduleInstance);
            this.moduleStates.set(moduleId, {
                loaded: true,
                loadedAt: Date.now(),
                state: 'active'
            });
            
            console.log(`✅ Module loaded: ${moduleId}`);
            this.emit('moduleLoaded', { moduleId, instance: moduleInstance });
            
            return moduleInstance;
            
        } catch (error) {
            console.error(`❌ Failed to load module ${moduleId}:`, error);
            this.moduleStates.set(moduleId, {
                loaded: false,
                error: error.message,
                state: 'error'
            });
            throw error;
        }
    }

    async createModuleInstance(moduleId, moduleDef) {
        // Create dependency injection container
        const dependencies = {};
        for (const depId of moduleDef.dependencies) {
            dependencies[this.getModuleName(depId)] = this.modules.get(depId);
        }
        
        // Create module factory
        const moduleFactory = this.createModuleFactory(moduleId, moduleDef);
        
        // Create instance with dependencies
        const instance = await moduleFactory.create(dependencies);
        
        // Add module metadata
        instance._moduleId = moduleId;
        instance._dependencies = moduleDef.dependencies;
        instance._description = moduleDef.description;
        
        return instance;
    }

    createModuleFactory(moduleId, moduleDef) {
        // This is a factory pattern implementation
        // In a real implementation, these would be actual module classes
        
        const factories = {
            'core/config-manager': () => new ConfigManager(),
            'core/activation-manager': (deps) => new ActivationManager(deps),
            'core/command-registry': (deps) => new CommandRegistry(deps),
            'core/webview-manager': (deps) => new WebviewManager(deps),
            'ai/orchestrator': (deps) => new AIOrchestrator(deps),
            'ai/providers/registry': (deps) => new ProviderRegistry(deps),
            'ai/providers/ollama': (deps) => new OllamaProvider(deps),
            'ai/providers/huggingface': (deps) => new HuggingFaceProvider(deps),
            'ai/providers/vigthoria-oai1': (deps) => new VigthoriaoAI1Provider(deps),
            'modes/ask-mode': (deps) => new AskMode(deps),
            'modes/build-mode': (deps) => new BuildMode(deps),
            'modes/agent-mode': (deps) => new AgentMode(deps),
            'modes/operator-mode': (deps) => new OperatorMode(deps),
            'agents/sub-agent-manager': (deps) => new SubAgentManager(deps),
            'agents/capabilities-engine': (deps) => new CapabilitiesEngine(deps),
            'ui/sidebar-provider': (deps) => new SidebarProvider(deps),
            'ui/chat-interface': (deps) => new ChatInterface(deps),
            'ui/status-bar': (deps) => new StatusBar(deps),
            'workspace/file-manager': (deps) => new FileManager(deps),
            'workspace/context-manager': (deps) => new ContextManager(deps),
            'workspace/project-intelligence': (deps) => new ProjectIntelligence(deps),
            'security/sandbox-manager': (deps) => new SandboxManager(deps),
            'security/auth-manager': (deps) => new AuthManager(deps),
            'performance/optimizer': (deps) => new PerformanceOptimizer(deps),
            'performance/memory-manager': (deps) => new MemoryManager(deps),
            'utils/logger': () => new Logger(),
            'utils/metrics-collector': (deps) => new MetricsCollector(deps),
            'utils/event-bus': () => new EventBus()
        };
        
        const factory = factories[moduleId];
        if (!factory) {
            // Return a generic module factory
            return {
                create: (dependencies) => new GenericModule(moduleId, moduleDef, dependencies)
            };
        }
        
        return {
            create: (dependencies) => factory(dependencies)
        };
    }

    getModule(moduleId) {
        return this.modules.get(moduleId);
    }

    getModuleName(moduleId) {
        return moduleId.split('/').pop().replace(/-([a-z])/g, (g) => g[1].toUpperCase());
    }

    async unloadModule(moduleId) {
        const module = this.modules.get(moduleId);
        if (!module) {
            console.log(`⚠️ Module ${moduleId} not loaded`);
            return;
        }
        
        console.log(`🔄 Unloading module: ${moduleId}`);
        
        try {
            // Call cleanup if available
            if (typeof module.cleanup === 'function') {
                await module.cleanup();
            }
            
            // Remove from registry
            this.modules.delete(moduleId);
            this.moduleStates.set(moduleId, {
                loaded: false,
                unloadedAt: Date.now(),
                state: 'unloaded'
            });
            
            console.log(`✅ Module unloaded: ${moduleId}`);
            this.emit('moduleUnloaded', { moduleId });
            
        } catch (error) {
            console.error(`❌ Failed to unload module ${moduleId}:`, error);
            throw error;
        }
    }

    async reloadModule(moduleId) {
        console.log(`🔄 Reloading module: ${moduleId}`);
        
        await this.unloadModule(moduleId);
        await this.loadModule(moduleId);
        
        console.log(`✅ Module reloaded: ${moduleId}`);
    }

    getModuleStatus(moduleId) {
        const state = this.moduleStates.get(moduleId);
        const instance = this.modules.get(moduleId);
        
        return {
            moduleId,
            loaded: !!instance,
            state: state?.state || 'unknown',
            loadedAt: state?.loadedAt,
            unloadedAt: state?.unloadedAt,
            error: state?.error,
            dependencies: this.moduleDefinitions[moduleId]?.dependencies || [],
            description: this.moduleDefinitions[moduleId]?.description || ''
        };
    }

    getAllModuleStatuses() {
        const statuses = {};
        for (const moduleId of Object.keys(this.moduleDefinitions)) {
            statuses[moduleId] = this.getModuleStatus(moduleId);
        }
        return statuses;
    }

    validateDependencies() {
        const issues = [];
        
        for (const [moduleId, moduleDef] of Object.entries(this.moduleDefinitions)) {
            for (const dependency of moduleDef.dependencies) {
                if (!this.moduleDefinitions[dependency]) {
                    issues.push({
                        type: 'missing_dependency',
                        module: moduleId,
                        dependency: dependency
                    });
                }
            }
        }
        
        return issues;
    }

    generateDependencyGraph() {
        const graph = {
            nodes: [],
            edges: []
        };
        
        // Add nodes
        for (const [moduleId, moduleDef] of Object.entries(this.moduleDefinitions)) {
            graph.nodes.push({
                id: moduleId,
                label: this.getModuleName(moduleId),
                priority: moduleDef.priority,
                description: moduleDef.description,
                loaded: this.modules.has(moduleId)
            });
        }
        
        // Add edges
        for (const [moduleId, moduleDef] of Object.entries(this.moduleDefinitions)) {
            for (const dependency of moduleDef.dependencies) {
                graph.edges.push({
                    from: dependency,
                    to: moduleId,
                    type: 'dependency'
                });
            }
        }
        
        return graph;
    }
}

/**
 * 🧩 GENERIC MODULE BASE CLASS
 * Provides common functionality for all modules
 */
class GenericModule extends EventEmitter {
    constructor(moduleId, moduleDef, dependencies) {
        super();
        
        this.moduleId = moduleId;
        this.moduleDef = moduleDef;
        this.dependencies = dependencies;
        this.initialized = false;
        this.state = 'created';
    }

    async initialize() {
        if (this.initialized) return;
        
        console.log(`🚀 Initializing module: ${this.moduleId}`);
        
        try {
            await this.onInitialize();
            this.initialized = true;
            this.state = 'initialized';
            
            console.log(`✅ Module initialized: ${this.moduleId}`);
            this.emit('initialized');
            
        } catch (error) {
            console.error(`❌ Failed to initialize module ${this.moduleId}:`, error);
            this.state = 'error';
            throw error;
        }
    }

    async onInitialize() {
        // Override in specific modules
    }

    async cleanup() {
        console.log(`🧹 Cleaning up module: ${this.moduleId}`);
        
        try {
            await this.onCleanup();
            this.state = 'cleaned';
            
            console.log(`✅ Module cleaned up: ${this.moduleId}`);
            this.emit('cleaned');
            
        } catch (error) {
            console.error(`❌ Failed to cleanup module ${this.moduleId}:`, error);
            throw error;
        }
    }

    async onCleanup() {
        // Override in specific modules
    }

    getStatus() {
        return {
            moduleId: this.moduleId,
            initialized: this.initialized,
            state: this.state,
            dependencies: Object.keys(this.dependencies)
        };
    }
}

// Placeholder module classes for the factory
class ConfigManager extends GenericModule {}
class ActivationManager extends GenericModule {}
class CommandRegistry extends GenericModule {}
class WebviewManager extends GenericModule {}
class AIOrchestrator extends GenericModule {}
class ProviderRegistry extends GenericModule {}
class OllamaProvider extends GenericModule {}
class HuggingFaceProvider extends GenericModule {}
class VigthoriaoAI1Provider extends GenericModule {}
class AskMode extends GenericModule {}
class BuildMode extends GenericModule {}
class AgentMode extends GenericModule {}
class OperatorMode extends GenericModule {}
class SubAgentManager extends GenericModule {}
class CapabilitiesEngine extends GenericModule {}
class SidebarProvider extends GenericModule {}
class ChatInterface extends GenericModule {}
class StatusBar extends GenericModule {}
class FileManager extends GenericModule {}
class ContextManager extends GenericModule {}
class ProjectIntelligence extends GenericModule {}
class SandboxManager extends GenericModule {}
class AuthManager extends GenericModule {}
class PerformanceOptimizer extends GenericModule {}
class MemoryManager extends GenericModule {}
class Logger extends GenericModule {}
class MetricsCollector extends GenericModule {}
class EventBus extends GenericModule {}

module.exports = { 
    ModularArchitectureManager, 
    GenericModule,
    // Export all module classes for use in actual implementations
    ConfigManager,
    ActivationManager,
    CommandRegistry,
    WebviewManager,
    AIOrchestrator,
    ProviderRegistry,
    OllamaProvider,
    HuggingFaceProvider,
    VigthoriaoAI1Provider,
    AskMode,
    BuildMode,
    AgentMode,
    OperatorMode,
    SubAgentManager,
    CapabilitiesEngine,
    SidebarProvider,
    ChatInterface,
    StatusBar,
    FileManager,
    ContextManager,
    ProjectIntelligence,
    SandboxManager,
    AuthManager,
    PerformanceOptimizer,
    MemoryManager,
    Logger,
    MetricsCollector,
    EventBus
};
