"""Application settings for <<project_name>>."""

import os
import tomllib
from typing import Any

from dotenv import load_dotenv
from pydantic import BaseModel, Field

from common.files import get_project_path

BASE_DIR = get_project_path()

# 自动加载项目根目录的 .env 文件
load_dotenv(BASE_DIR.joinpath(".env"), override=False)
env_name = os.getenv("ENV", "dev").lower()
env_file = BASE_DIR.joinpath(f".env.{env_name}")
load_dotenv(env_file, override=True)


class LogConfig(BaseModel):
    """日志配置 (logging configuration)，对应 config.*.toml 的 [log] 段."""

    # 日志级别 / log level: debug / info / warning / error / critical
    level: str = Field(default="info")

    # 输出格式 / output format: "console" (彩色人类可读) 或 "json" (结构化)
    format: str = Field(default="json")

    # 日志目录 / log directory (留空 = 不写文件)
    directory: str = Field(default="logs")

    # 显式文件路径 / explicit file path (优先级高于 directory；留空 = 用 directory + 默认名)
    file: str = Field(default="")

    # 是否同时输出到控制台 / also log to console
    log_in_console: bool = Field(default=True)

    # 是否附带 文件名/函数/行号 / include filename/func/lineno
    show_line: bool = Field(default=False)

    # 单文件最大体积 (MB) / max size per file before rotation
    max_size: int = Field(default=10)

    # 保留的轮转文件数量 / number of rotated backups to keep
    max_backups: int = Field(default=10)

    # 旧日志保留天数 / days to keep old log files (0 = 永久)
    max_age: int = Field(default=30)

    # 轮转后是否 gzip 压缩 / gzip-compress rotated files
    compress: bool = Field(default=True)


class Settings:
    """Application settings."""

    def __init__(self) -> None:
        """Initialize settings."""
        self.project_name = "<<project_name>>"
        self.version = "<<project_version>>"
        self.debug = self._get_bool_env("DEBUG", False)

        # Paths
        self.base_dir = BASE_DIR
        self.src_dir = self.base_dir / "src"
        self.config_dir = self.base_dir / "config"

        # Load config from TOML
        self._load_config()

    def _load_config(self) -> None:
        """Load configuration from TOML file."""
        config_file = self.config_dir / f"config.{env_name}.toml"
        if not config_file.exists():
            config_file = self.config_dir / "config.example.toml"

        config_data: dict[str, Any] = {}
        if config_file.exists():
            with open(config_file, "rb") as f:
                config_data = tomllib.load(f)

        # 加载 [log] 段 (load the [log] section)
        self.log = LogConfig(**config_data.get("log", {}))

    @staticmethod
    def _get_bool_env(key: str, default: bool = False) -> bool:
        """Get boolean environment variable."""
        value = os.getenv(key, str(default)).lower()
        return value in ("true", "1", "yes", "on")

    @staticmethod
    def _get_env(key: str, default: Any = None) -> Any:
        """Get environment variable with default."""
        return os.getenv(key, default)


# Global settings instance
settings = Settings()
