from pydantic_settings import BaseSettings
from typing import Optional, Dict, Any
from sqlalchemy.orm import Session


class Settings(BaseSettings):
    """应用配置类"""
    # 应用基本配置
    APP_NAME: str = "智能算法展示平台"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = True
    
    # 数据库配置
    DATABASE_URL: str = "postgresql://admin:password@localhost:5432/algorithm_db"
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379/0"
    
    # MinIO配置
    MINIO_ENDPOINT: str = "localhost:9000"
    MINIO_ACCESS_KEY: str = "minioadmin"
    MINIO_SECRET_KEY: str = "minioadmin"
    MINIO_BUCKET_NAME: str = "algorithm-data"
    MINIO_SECURE: bool = False
    
    # JWT配置
    SECRET_KEY: str = "your-secret-key-here"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    
    # OpenAI配置
    OPENAI_API_KEY: Optional[str] = None
    OPENAI_MODEL: str = "gpt-3.5-turbo"
    
    # CORS配置
    CORS_ORIGINS: list = ["*"]
    
    # API配置
    API_V1_STR: str = "/api/v1"
    
    # 部署配置
    DEPLOYMENT_MODE: str = "local"  # 部署模式：docker 或 local
    
    # Gitea 配置
    GITEA_SERVER_URL: str = ""
    GITEA_ACCESS_TOKEN: str = ""
    GITEA_DEFAULT_OWNER: str = ""
    GITEA_REPO_PREFIX: str = "AI"
    
    # 服务管理配置
    SERVICE_MANAGEMENT: Dict[str, Any] = {
        "mode": "supervisor",  # 服务管理模式：local, docker, supervisor
        "service_root_dir": "/opt/ai-services",
        "supervisor_config_dir": "/etc/supervisor/conf.d",
    }
    
    class Config:
        env_file = ".env"
        case_sensitive = True
        extra = "allow"  # 允许额外的环境变量

    def get_config(self, config_key: str, default: Any = None) -> Any:
        """获取配置，优先级：环境变量 > 数据库 > 文件默认值
        
        Args:
            config_key: 配置键
            default: 默认值
            
        Returns:
            配置值
        """
        # 1. 先从环境变量获取
        env_key = config_key.upper().replace('.', '_')
        env_value = getattr(self, env_key, None)
        if env_value is not None:
            return env_value
        
        # 2. 从数据库获取
        try:
            from app.models.database import SessionLocal
            from app.models.models import ServiceConfig
            
            db: Session = SessionLocal()
            try:
                config = db.query(ServiceConfig).filter_by(
                    config_key=config_key,
                    status="active"
                ).first()
                if config:
                    return config.config_value
            finally:
                db.close()
        except Exception as e:
            # 数据库连接失败时，返回默认值
            print(f"Failed to load config from database: {str(e)}")
        
        # 3. 返回默认值
        return default


# 创建全局配置实例
settings = Settings()
