"""
项目配置模块 — 读取并校验根目录 env.yaml

使用方式：
    from engine.common.config import config

    db = config.db
    print(db.host, db.port, db.name)
    print(config.redis.url)
    print(config.logging.level)
"""

from pathlib import Path
from typing import Optional

import yaml
from pydantic import BaseModel, Field


class DBConfig(BaseModel):
    """TimescaleDB / PostgreSQL 连接配置"""

    host: str
    port: int = 5432
    name: str
    user: str
    password: str


class RedisConfig(BaseModel):
    """Redis 连接配置"""

    url: str = "redis://localhost:6379"
    publish_enabled: bool = True


class LoggingConfig(BaseModel):
    """日志配置"""

    level: str = "debug"  # trace / debug / info / warn / error / fatal
    node_env: str = Field(default="development", alias="node_env")

    class Config:
        populate_by_name = True


class AppConfig(BaseModel):
    """应用配置聚合"""

    db: DBConfig
    redis: RedisConfig
    logging: LoggingConfig


def load_config(config_path: Optional[Path] = None) -> AppConfig:
    """从 env.yaml 加载并校验配置

    Args:
        config_path: 显式指定路径；为 None 时自动查找项目根目录 env.yaml
    """
    if config_path is None:
        # engine/common/config.py → engine/ (parent of common/) → 根目录 env.yaml
        config_path = Path(__file__).resolve().parent.parent / "env.yaml"

    with open(config_path) as f:
        raw = yaml.safe_load(f)

    return AppConfig(**raw)


# ── 模块级单例 ──
config = load_config()
