# -*- coding: utf-8 -*-
"""
核心配置模块
使用 Pydantic v2 Settings 管理所有环境变量，支持 .env 文件自动加载。
"""

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """应用全局配置，所有敏感信息通过环境变量注入，禁止硬编码。"""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
    )

    # ---- 应用基础 ----
    APP_NAME: str = "SHBL-CRM"
    APP_VERSION: str = "2.0.0"
    DEBUG: bool = False

    # ---- 数据库 (PostgreSQL + asyncpg) ----
    DB_HOST: str = "127.0.0.1"
    DB_PORT: int = 5432
    DB_USER: str = "crm_admin"
    DB_PASSWORD: str = "change_me_in_production"
    DB_NAME: str = "shbl_crm"

    @property
    def DATABASE_URL(self) -> str:
        """构造异步 PostgreSQL 连接字符串 (asyncpg 驱动)"""
        return (
            f"postgresql+asyncpg://{self.DB_USER}:{self.DB_PASSWORD}"
            f"@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
        )

    @property
    def DATABASE_URL_SYNC(self) -> str:
        """同步连接字符串，仅供 Alembic 迁移使用"""
        return (
            f"postgresql+psycopg2://{self.DB_USER}:{self.DB_PASSWORD}"
            f"@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
        )

    # ---- JWT 安全 ----
    SECRET_KEY: str = "REPLACE_WITH_RANDOM_64_CHAR_HEX"
    JWT_ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24  # 24小时

    # ---- CORS 白名单 (严格模式，禁止 "*") ----
    CORS_ORIGINS: list[str] = [
        "http://localhost:5173",   # Vite 开发服务器
        "http://localhost:8080",   # Nginx 生产前端
    ]

    # ---- AI 服务 (Dify BaaS 平台) ----
    DIFY_BASE_URL: str = "http://192.168.1.88/v1"
    DIFY_LOG_APP_API_KEY: str = ""       # 日志分析 App (completion)
    DIFY_REPORT_APP_API_KEY: str = ""    # 月度报告 App (completion)


# 全局单例，其他模块通过 from app.core.config import settings 引用
settings = Settings()
