import os
import yaml
from typing import Dict, Any, Optional

class EnsembleConfig:
    _instance: Optional['EnsembleConfig'] = None
    _config: Dict[str, Any] = {}
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(EnsembleConfig, cls).__new__(cls)
            cls._instance._load_config()
        return cls._instance
    
    def _load_config(self):
        """Load configuration from YAML file."""
        config_path = os.path.join(os.path.dirname(__file__), 'ensemble_config.yaml')
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                self._config = yaml.safe_load(f)
            # print(f"✅ Loaded ensemble config from {config_path}")
        except Exception as e:
            print(f"❌ Failed to load ensemble config: {e}")
            self._config = {}
    
    def get(self, key: str, default: Any = None) -> Any:
        """Get configuration value by key (supports dot notation for nested keys)."""
        keys = key.split('.')
        value = self._config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default

# Singleton accessor
def get_config() -> EnsembleConfig:
    return EnsembleConfig()

if __name__ == "__main__":
    # Test
    cfg = get_config()
    print(f"Weights: {cfg.get('engine_weights')}")
    print(f"Team Weight: {cfg.get('engine_weights.team')}")
