"""Factory for loading and managing strategies."""

import importlib
import inspect
from typing import Dict, Type, Optional
from .interface import Strategy


class StrategyFactory:
    """Factory for loading trading strategies.
    
    Usage:
        factory = StrategyFactory()
        factory.register_strategy(MyStrategy)
        strategy = factory.create('my_strategy', config)
    """
    
    def __init__(self):
        self._strategies: Dict[str, Type[Strategy]] = {}
        # Register built-in strategies
        self._register_builtin_strategies()
    
    def _register_builtin_strategies(self) -> None:
        """Register built-in strategies."""
        try:
            from .ma_crossover import SimpleMACrossover
            self.register_strategy(SimpleMACrossover)
        except ImportError as e:
            print(f"Warning: Could not load SimpleMACrossover: {e}")
    
    def register_strategy(self, strategy_class: Type[Strategy]) -> None:
        """Register a strategy class.
        
        Args:
            strategy_class: Strategy class to register
        """
        if not issubclass(strategy_class, Strategy):
            raise TypeError(f"{strategy_class} must be a subclass of Strategy")
        
        strategy_id = strategy_class.id
        self._strategies[strategy_id] = strategy_class
        print(f"Registered strategy: {strategy_id} ({strategy_class.name})")
    
    def create(
        self,
        strategy_id: str,
        config: Optional[Dict] = None
    ) -> Strategy:
        """Create a strategy instance.
        
        Args:
            strategy_id: Strategy identifier
            config: Strategy configuration
            
        Returns:
            Initialized strategy instance
            
        Raises:
            ValueError: If strategy not found
        """
        strategy_class = self._strategies.get(strategy_id)
        if not strategy_class:
            available = ', '.join(self._strategies.keys())
            raise ValueError(
                f"Unknown strategy: {strategy_id}. Available: {available}"
            )
        
        strategy = strategy_class(config)
        strategy.validate()
        return strategy
    
    def list_available(self) -> Dict[str, str]:
        """List available strategies.
        
        Returns:
            Dictionary of strategy_id -> strategy_name
        """
        return {
            sid: cls.name 
            for sid, cls in self._strategies.items()
        }
    
    def get_strategy_info(self, strategy_id: str) -> Optional[Dict]:
        """Get strategy information.
        
        Args:
            strategy_id: Strategy identifier
            
        Returns:
            Strategy metadata or None
        """
        strategy_class = self._strategies.get(strategy_id)
        if not strategy_class:
            return None
        
        return {
            'id': strategy_class.id,
            'name': strategy_class.name,
            'version': strategy_class.version,
            'description': strategy_class.description,
        }
