from pydantic_settings import BaseSettings
from pathlib import Path
import re
from typing import Literal


def _load_ruoyi_mysql_defaults() -> dict:
    """从主项目开发配置中提取 MySQL 连接默认值。"""
    project_root = Path(__file__).resolve().parents[2]
    config_path = project_root / "ruoyi-admin" / "src" / "main" / "resources" / "application-dev.yml"
    if not config_path.exists():
        return {}

    text = config_path.read_text(encoding="utf-8")
    match = re.search(
        r"master:\s*\n"
        r"\s*url:\s*jdbc:mysql://(?P<host>[^:/?#]+):(?P<port>\d+)/(?P<database>[^?\s]+)[^\n]*\n"
        r"\s*username:\s*(?P<username>[^\n]+)\n"
        r"\s*password:\s*(?P<password>[^\n]+)",
        text,
    )
    if not match:
        return {}

    return {key: value.strip() for key, value in match.groupdict().items()}


MYSQL_DEFAULTS = _load_ruoyi_mysql_defaults()
LSFX_DEFAULT_CCDI_DB_HOST = "116.62.17.81"
LSFX_DEFAULT_CCDI_DB_PORT = 3307


class Settings(BaseSettings):
    """全局配置类"""

    # 应用配置
    APP_NAME: str = "流水分析Mock服务"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = True

    # 服务器配置
    HOST: str = "0.0.0.0"
    PORT: int = 8000

    # 模拟配置
    PARSE_DELAY_SECONDS: int = 4  # 文件解析延迟秒数
    MAX_FILE_SIZE: int = 10485760  # 10MB
    RULE_HIT_MODE: Literal["subset", "all"] = "subset"

    # 测试数据配置
    INITIAL_PROJECT_ID: int = 1000
    INITIAL_LOG_ID: int = 10000

    # 员工库只读配置
    CCDI_DB_HOST: str = LSFX_DEFAULT_CCDI_DB_HOST
    CCDI_DB_PORT: int = LSFX_DEFAULT_CCDI_DB_PORT
    CCDI_DB_NAME: str = MYSQL_DEFAULTS.get("database", "")
    CCDI_DB_USERNAME: str = MYSQL_DEFAULTS.get("username", "")
    CCDI_DB_PASSWORD: str = MYSQL_DEFAULTS.get("password", "")
    CCDI_DB_CONNECT_TIMEOUT_SECONDS: int = 5

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


settings = Settings()
