"""
应用配置模块
"""
from typing import List, Optional
from pydantic import field_validator, Field
from pydantic_settings import BaseSettings
from functools import lru_cache
import os


class Settings(BaseSettings):
    """应用配置类"""
    
    # 应用基础配置
    APP_NAME: str = "SSO认证中心"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = False
    SECRET_KEY: str
    ALGORITHM: str = "HS256"
    
    # 服务器配置
    HOST: str = "0.0.0.0"
    PORT: int = 8000
    RELOAD: bool = False
    
    # 数据库配置
    DATABASE_URL: str
    DATABASE_ECHO: bool = False
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379/0"
    REDIS_PASSWORD: Optional[str] = None
    
    # JWT配置
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    REFRESH_TOKEN_EXPIRE_DAYS: int = 30
    JWT_SECRET_KEY: str
    
    # OAuth2配置
    OAUTH2_AUTHORIZATION_CODE_EXPIRE_MINUTES: int = 10
    OAUTH2_ACCESS_TOKEN_EXPIRE_MINUTES: int = 120
    OAUTH2_REFRESH_TOKEN_EXPIRE_DAYS: int = 30
    
    # 邮件配置
    SMTP_HOST: Optional[str] = None
    SMTP_PORT: int = 587
    SMTP_USER: Optional[str] = None
    SMTP_PASSWORD: Optional[str] = None
    SMTP_TLS: bool = True
    SMTP_SSL: bool = False
    
    # 文件上传配置
    UPLOAD_DIR: str = "./uploads"
    MAX_FILE_SIZE: int = 5242880  # 5MB
    ALLOWED_EXTENSIONS: list[str] = Field(default_factory=lambda: ["jpg", "jpeg", "png", "gif"])
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "./logs/app.log"
    
    # CORS配置
    CORS_ORIGINS: list[str] = Field(default_factory=list)
    CORS_CREDENTIALS: bool = True
    CORS_METHODS: list[str] = Field(default_factory=lambda: ["*"])
    CORS_HEADERS: list[str] = Field(default_factory=lambda: ["*"])
    
    # 安全配置
    BCRYPT_ROUNDS: int = 12
    PASSWORD_MIN_LENGTH: int = 8
    MAX_LOGIN_ATTEMPTS: int = 5
    LOCKOUT_DURATION_MINUTES: int = 30
    
    # 缓存配置
    CACHE_TTL: int = 3600
    SESSION_TTL: int = 86400
    
    # Celery配置
    CELERY_BROKER_URL: str = "redis://localhost:6379/1"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/2"
    
    # Milvus配置
    MILVUS_HOST: str = "192.168.92.61"
    MILVUS_PORT: int = 19530
    MILVUS_DB: str = "lq_db"
    MILVUS_USER: Optional[str] = "lq"
    MILVUS_PASSWORD: Optional[str] = "lq123456!"
    
    # MinIO配置
    MINIO_ENDPOINT: str = "192.168.91.15:19000"
    MINIO_ACCESS_KEY: str = "HVFOa38zUDg3X6c14hpH"
    MINIO_SECRET_KEY: str = "ilVITuWEmjG0YDBAWspSG6UniHpEoMDECSuCo0f1"
    MINIO_BUCKET_NAME: str = "aidata"
    MINIO_USE_SSL: bool = False
    MINIO_BASE_PATH: str = "sampledata"
    
    # MinERU配置
    MINERU_TOKEN: str = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiI1MzgwMDYyNSIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc2Nzg1OTg5NywiY2xpZW50SWQiOiJsa3pkeDU3bnZ5MjJqa3BxOXgydyIsInBob25lIjoiMTgwMzA5ODIxNTQiLCJvcGVuSWQiOm51bGwsInV1aWQiOiI0NTYyZTUyNi1iZjE3LTRhMmItODExMi04YmM5ZjNjYzMwZGMiLCJlbWFpbCI6IiIsImV4cCI6MTc2OTA2OTQ5N30.mNH7afPPANNQq_BRsBOlbk-2P7e_ewdfzPQXO4woeoT15mDEbPKc45Auk_BuRuNaAS-Gm2GK3qKGjQ2VDtepvA"
    MINERU_API_APPLY: str = "https://mineru.net/api/v4/file-urls/batch"
    MINERU_API_BATCH_RESULT: str = "https://mineru.net/api/v4/extract-results/batch/{}"
    
    # embedding模型配置
    EMBEDDING_BASE_URL: str = "http://192.168.91.253:9003/v1"
    EMBEDDING_MODEL: str = "Qwen3-Embedding-8B"
    EMBEDDING_API_KEY: str = "dummy"
    
    @field_validator("ALLOWED_EXTENSIONS", mode="before")
    @classmethod
    def parse_allowed_extensions(cls, v):
        if isinstance(v, str):
            return [ext.strip() for ext in v.split(",")]
        return v
    
    @field_validator("CORS_ORIGINS", mode="before")
    @classmethod
    def parse_cors_origins(cls, v):
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v
    
    @field_validator("CORS_METHODS", mode="before")
    @classmethod
    def parse_cors_methods(cls, v):
        if isinstance(v, str):
            if v == "*":
                return ["*"]
            return [method.strip() for method in v.split(",")]
        return v
    
    @field_validator("CORS_HEADERS", mode="before")
    @classmethod
    def parse_cors_headers(cls, v):
        if isinstance(v, str):
            if v == "*":
                return ["*"]
            return [header.strip() for header in v.split(",")]
        return v
    
    @property
    def allowed_extensions_list(self) -> List[str]:
        """获取允许的文件扩展名列表"""
        if isinstance(self.ALLOWED_EXTENSIONS, str):
            return [ext.strip() for ext in self.ALLOWED_EXTENSIONS.split(",")]
        return self.ALLOWED_EXTENSIONS
    
    @property
    def cors_origins_list(self) -> List[str]:
        """获取CORS允许的源列表"""
        if isinstance(self.CORS_ORIGINS, str):
            return [origin.strip() for origin in self.CORS_ORIGINS.split(",")]
        return self.CORS_ORIGINS
    
    @property
    def cors_methods_list(self) -> List[str]:
        """获取CORS允许的方法列表"""
        if isinstance(self.CORS_METHODS, str):
            if self.CORS_METHODS == "*":
                return ["*"]
            return [method.strip() for method in self.CORS_METHODS.split(",")]
        return self.CORS_METHODS
    
    @property
    def cors_headers_list(self) -> List[str]:
        """获取CORS允许的头部列表"""
        if isinstance(self.CORS_HEADERS, str):
            if self.CORS_HEADERS == "*":
                return ["*"]
            return [header.strip() for header in self.CORS_HEADERS.split(",")]
        return self.CORS_HEADERS
    
    class Config:
        env_file = os.path.join(os.path.dirname(__file__), ".env")
        case_sensitive = True


@lru_cache()
def get_settings() -> Settings:
    """获取配置实例"""
    return Settings()


# 全局配置实例
settings = get_settings()