from pydantic_settings import BaseSettings
from pydantic import field_validator
from functools import lru_cache


class Settings(BaseSettings):
    """应用配置类，管理所有环境变量和配置项"""

    APP_NAME: str = "海洋项目管理系统"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = False

    DB_HOST: str = "localhost"
    DB_PORT: int = 3306
    DB_USER: str = "root"
    DB_PASSWORD: str | None = None
    DB_NAME: str = "project_manager"
    DB_CHARSET: str = "utf8mb4"

    SECRET_KEY: str | None = None
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440

    CORS_ORIGINS: list[str] = ["http://localhost:3000", "http://127.0.0.1:3000"]

    @field_validator("DB_PASSWORD", "SECRET_KEY")
    @classmethod
    def validate_sensitive_config(cls, v, info):
        """验证敏感配置项是否已设置"""
        if v is None:
            raise ValueError(
                f"{info.field_name} 未设置，请在环境变量或.env文件中配置"
            )
        return v

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


@lru_cache()
def get_settings() -> Settings:
    """获取Settings单例实例，使用LRU缓存提高性能"""
    return Settings()
