"""Dynamic module loading and management"""

import logging
import importlib
import inspect
from pathlib import Path
from typing import Dict, List, Optional, Type

from .base_module import BaseModule

logger = logging.getLogger(__name__)

class ModuleLoader:
    """Dynamically loads and manages mod modules"""
    
    def __init__(self):
        self.modules: Dict[str, Type[BaseModule]] = {}
        self.module_instances: Dict[str, BaseModule] = {}
    
    def discover_modules(self):
        """Discover and load all available modules"""
        modules_dir = Path(__file__).parent
        
        # Import all module files
        for module_file in modules_dir.glob("*_module.py"):
            module_name = module_file.stem
            
            try:
                # Import the module
                module = importlib.import_module(f"src.modules.{module_name}")
                
                # Find classes that inherit from BaseModule
                for name, obj in inspect.getmembers(module):
                    if inspect.isclass(obj) and issubclass(obj, BaseModule) and obj != BaseModule:
                        self.modules[name] = obj
                        logger.info(f"Loaded module: {name}")
                        
            except Exception as e:
                logger.error(f"Failed to load module {module_name}: {e}")
    
    def get_available_modules(self) -> List[BaseModule]:
        """Get list of available module instances"""
        instances = []
        
        for name, module_class in self.modules.items():
            if name not in self.module_instances:
                self.module_instances[name] = module_class()
            instances.append(self.module_instances[name])
        
        return instances
    
    def get_module(self, name: str) -> Optional[BaseModule]:
        """Get a specific module instance by name"""
        if name in self.module_instances:
            return self.module_instances[name]
        
        # Try to find by class name
        for module_name, module_class in self.modules.items():
            if module_name == name or module_class.__name__ == name:
                if module_name not in self.module_instances:
                    self.module_instances[module_name] = module_class()
                return self.module_instances[module_name]
        
        return None