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


class Settings(BaseSettings):
    """应用配置类"""

    # 应用基本信息
    APP_NAME: str = Field(default="资产管理系统", description="应用名称")
    APP_VERSION: str = Field(default="1.0.0", description="应用版本")
    APP_ENVIRONMENT: str = Field(default="development", description="运行环境")
    DEBUG: bool = Field(default=False, description="调试模式")
    API_V1_PREFIX: str = Field(default="/api/v1", description="API V1 前缀")

    # 服务器配置
    HOST: str = Field(default="0.0.0.0", description="服务器地址")
    PORT: int = Field(default=8000, description="服务器端口")

    # 数据库配置
    DATABASE_URL: str = Field(
        default="postgresql+asyncpg://postgres:postgres@localhost:5432/asset_management",
        description="数据库连接URL"
    )
    DATABASE_ECHO: bool = Field(default=False, description="是否打印SQL语句")

    # Redis配置
    REDIS_URL: str = Field(default="redis://localhost:6379/0", description="Redis连接URL")
    REDIS_MAX_CONNECTIONS: int = Field(default=50, description="Redis最大连接数")

    # JWT配置
    SECRET_KEY: str = Field(default="your-secret-key-change-in-production", description="JWT密钥")
    ALGORITHM: str = Field(default="HS256", description="JWT算法")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(default=15, description="访问令牌过期时间（分钟）")
    REFRESH_TOKEN_EXPIRE_DAYS: int = Field(default=7, description="刷新令牌过期时间（天）")

    # CORS配置
    CORS_ORIGINS: List[str] = Field(
        default=["http://localhost:5173", "http://localhost:3000"],
        description="允许的跨域来源"
    )
    CORS_ALLOW_CREDENTIALS: bool = Field(default=True, description="允许携带凭证")
    CORS_ALLOW_METHODS: List[str] = Field(default=["*"], description="允许的HTTP方法")
    CORS_ALLOW_HEADERS: List[str] = Field(default=["*"], description="允许的请求头")

    # 文件上传配置
    UPLOAD_DIR: str = Field(default="uploads", description="上传文件目录")
    MAX_UPLOAD_SIZE: int = Field(default=10485760, description="最大上传大小（字节）")
    ALLOWED_EXTENSIONS: List[str] = Field(
        default=["png", "jpg", "jpeg", "gif", "pdf", "xlsx", "xls"],
        description="允许的文件扩展名"
    )

    # 验证码配置
    CAPTCHA_EXPIRE_SECONDS: int = Field(default=300, description="验证码过期时间（秒）")
    CAPTCHA_LENGTH: int = Field(default=4, description="验证码长度")

    # 日志配置
    LOG_LEVEL: str = Field(default="INFO", description="日志级别")
    LOG_FILE: str = Field(default="logs/app.log", description="日志文件路径")
    LOG_ROTATION: str = Field(default="500 MB", description="日志轮转大小")
    LOG_RETENTION: str = Field(default="10 days", description="日志保留时间")

    # 分页配置
    DEFAULT_PAGE_SIZE: int = Field(default=20, description="默认每页数量")
    MAX_PAGE_SIZE: int = Field(default=100, description="最大每页数量")

    # 二维码配置
    QR_CODE_DIR: str = Field(default="uploads/qrcodes", description="二维码保存目录")
    QR_CODE_SIZE: int = Field(default=300, description="二维码尺寸")
    QR_CODE_BORDER: int = Field(default=2, description="二维码边框")

    @field_validator("CORS_ORIGINS", mode="before")
    @classmethod
    def parse_cors_origins(cls, v: str) -> List[str]:
        """解析CORS来源"""
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v

    @field_validator("ALLOWED_EXTENSIONS", mode="before")
    @classmethod
    def parse_allowed_extensions(cls, v: str) -> List[str]:
        """解析允许的文件扩展名"""
        if isinstance(v, str):
            return [ext.strip() for ext in v.split(",")]
        return v

    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self.APP_ENVIRONMENT == "development"

    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return self.APP_ENVIRONMENT == "production"

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = True


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