from typing import Any, Dict, List, Optional, Union
from pydantic import AnyHttpUrl, validator
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    PROJECT_NAME: str = "Unified Authentication Platform"
    API_V1_STR: str = "/api/v1"
    
    # Database
    MYSQL_SERVER: str = "localhost"
    MYSQL_USER: str = "root"
    MYSQL_PASSWORD: str = "secret"
    MYSQL_DB: str = "uap_db"
    MYSQL_PORT: int = 3306
    DATABASE_URI: Optional[str] = None

    @validator("DATABASE_URI", pre=True)
    def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
        if isinstance(v, str):
            return v
        return f"mysql://{values.get('MYSQL_USER')}:{values.get('MYSQL_PASSWORD')}@{values.get('MYSQL_SERVER')}:{values.get('MYSQL_PORT')}/{values.get('MYSQL_DB')}"

    # Redis
    REDIS_HOST: str = "localhost"
    REDIS_PORT: int = 6379
    REDIS_DB: int = 0
    REDIS_PASSWORD: Optional[str] = None
    
    # Security
    SECRET_KEY: str = "change_me_in_production"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 129600  # ~90 days (3 months)
    ACCESS_TOKEN_EXPIRE_MINUTES_LONG: int = 525600  # 365 days (1 year)

    # Identity QR (AES-256-GCM payload for personal QR code)
    IDENTITY_QR_VALID_SECONDS: int = 60  # 1 minute
    # 32 字节 AES 密钥：64 位 hex（推荐）、Base64、或 UTF-8 恰 32 字符；生产环境务必替换
    IDENTITY_QR_ENCRYPTION_KEY: str = (
        "0f1e2d3c4b5a69788796a5b4c3d2e1f0deadbeefcafebabe0123456789abcdef"
    )

    # CORS
    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []

    @validator("BACKEND_CORS_ORIGINS", pre=True)
    def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
        if isinstance(v, str) and not v.startswith("["):
            return [i.strip() for i in v.split(",")]
        elif isinstance(v, (list, str)):
            return v
        raise ValueError(v)

    # Captcha
    CAPTCHA_EXPIRE_SECONDS: int = 600

    # SMS
    # SMS_PROVIDER: str = "mock"  # Options: "mock", "aliyun"
    SMS_PROVIDER: str = "aliyun"
    ALIYUN_ACCESS_KEY_ID: Optional[str] = "LTAI5tDScnqnCTKVPwLgHCqS"
    ALIYUN_ACCESS_KEY_SECRET: Optional[str] = "cRr1ThS29pycEiZ3nvCokZjswMEYP3"
    ALIYUN_SMS_SIGN_NAME: Optional[str] = "速通互联验证服务"
    ALIYUN_SMS_TEMPLATE_CODE: Optional[str] = "100001"
    
    # MinIO
    MINIO_ENDPOINT: str = "https://api.hnyunzhu.com:9004"
    MINIO_ACCESS_KEY: str = "1jC3nmjfWAyMGJ3pinbT"
    MINIO_SECRET_KEY: str = "6FHE9lzeQ6rZ3wIXSA9jGu8pGf49vgwT18NJ9XpO"
    MINIO_BUCKET_NAME: str = "unified-message-files"
    MINIO_DB_BACKUP_BUCKET_NAME: str = "unified-db-backups"
    MINIO_DISTRIBUTION_BUCKET_NAME: str = "unified-application-distribution"
    MINIO_UPDATE_BUCKET_NAME: str = "app-updates"  # 公开读桶，用于自建更新文件 update/
    MINIO_SECURE: bool = False

    # 登录页「下载客户端」跳转地址（通常为下载落地页）；不配则隐藏入口，不写数据库
    CLIENT_DOWNLOAD_URL_MOBILE: Optional[str] = "https://api.hnyunzhu.com/d/gAAAAABp3aYH7i4_dgAmlQLb-ruUiqbPyc5vH23EEB7pvIWEZHbBwekS1hfaWPqyew2QuqGfcPMtxGd7Zvei0_Ijv-LyPst1NAYv1skXP4LklYTAVjuCvRM%3D?platform=android"
    CLIENT_DOWNLOAD_URL_PC: Optional[str] = "https://api.hnyunzhu.com/d/gAAAAABp3aYH7i4_dgAmlQLb-ruUiqbPyc5vH23EEB7pvIWEZHbBwekS1hfaWPqyew2QuqGfcPMtxGd7Zvei0_Ijv-LyPst1NAYv1skXP4LklYTAVjuCvRM%3D?platform=windows"

    class Config:
        case_sensitive = True
        env_file = ".env"

settings = Settings()

