import os
import yaml
import logging
from pathlib import Path
from typing import Optional, Dict, Any

logger = logging.getLogger(__name__)


def _get_secret(key: str, fallback: str = None) -> Optional[str]:
    """从conf-man获取密钥"""
    try:
        from backend.integrations.secret_client import get_secret_client
        client = get_secret_client()
        value = client.get(key)
        if value:
            return value
    except Exception as e:
        logger.debug(f"Failed to get secret {key} from conf-man: {e}")
    
    if fallback:
        return fallback
    return None


class Config:
    """配置管理类"""
    
    _instance: Optional['Config'] = None
    _config: Dict[str, Any] = {}
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._load_config()
        return cls._instance
    
    def _load_config(self):
        """加载配置文件"""
        config_path = Path(__file__).parent.parent / "config" / "settings.yaml"
        
        if config_path.exists():
            with open(config_path, 'r', encoding='utf-8') as f:
                self._config = yaml.safe_load(f) or {}
        
        # 环境变量覆盖
        self._apply_env_overrides()
    
    def _apply_env_overrides(self):
        """应用环境变量覆盖"""
        # Database
        if db_url := os.getenv("DATABASE_URL"):
            self._config.setdefault("database", {})["url"] = db_url
        
        # OpenAI
        if api_key := os.getenv("OPENAI_API_KEY"):
            self._config.setdefault("llm", {})["api_key"] = api_key
        
        # DossierAI
        if dossierai_url := os.getenv("DOSSIERAI_URL"):
            self._config.setdefault("dossierai", {})["base_url"] = dossierai_url
        
        # SiliconFlow
        if sf_key := os.getenv("SILICONFLOW_API_KEY"):
            self._config.setdefault("siliconflow", {})["api_key"] = sf_key
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值，支持点号分隔的键"""
        keys = key.split(".")
        value = self._config
        
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k)
            else:
                return default
        
        return value if value is not None else default
    
    @property
    def database_url(self) -> str:
        return self.get("database.url", "sqlite:///./data/pm_agent.db")
    
    @property
    def dossierai_base_url(self) -> str:
        return self.get("dossierai.base_url", "http://localhost:4312/api/v1")
    
    @property
    def dossierai_timeout(self) -> int:
        return self.get("dossierai.timeout", 300)
    
    @property
    def llm_api_key(self) -> str:
        value = _get_secret("openai_key", os.getenv("OPENAI_API_KEY") or "")
        return value or ""
    
    @property
    def llm_model(self) -> str:
        return self.get("llm.model", "gpt-4")
    
    @property
    def backend_host(self) -> str:
        return self.get("backend.host", "0.0.0.0")
    
    @property
    def backend_port(self) -> int:
        return self.get("backend.port", 8000)
    
    @property
    def upload_max_file_size(self) -> int:
        return self.get("upload.max_file_size", 10485760)
    
    @property
    def upload_allowed_extensions(self) -> list:
        return self.get("upload.allowed_extensions", [])
    
    @property
    def siliconflow_api_key(self) -> str:
        value = _get_secret("siliconflow_key", os.getenv("SILICONFLOW_API_KEY") or "")
        return value or ""


# 全局配置实例
config = Config()
