"""配置模块。

所有 Settings 实例的字段和 @property 会被自动导出为模块级变量。
业务代码直接导入：

    from fastapi_admin.config import APP_PORT, ASYNCPG_DATABASE_URL
"""

from __future__ import annotations

from ._loader import load_config as _load_config

# 优先加载 TOML → os.environ（必须在 Settings 实例化之前）
_load_config()

from ._settings import app, jwt, db, redis, oss, llm, vlm, ocr, leaudit as _leaudit  # noqa: E402


def _export_settings(instance: object, prefix: str = "") -> dict[str, object]:
    """将 Settings 实例的所有字段和 @property 导出为模块级变量。"""
    result: dict[str, object] = {}

    # pydantic v2 model_fields
    model_fields = getattr(instance, "model_fields", None)
    if isinstance(model_fields, dict):
        for key in model_fields:
            if key.startswith("_"):
                continue
            result[key] = getattr(instance, key)

    # @property 和普通属性
    for key in dir(type(instance)):
        if key.startswith("_") or key in result:
            continue
        attr = getattr(type(instance), key, None)
        if attr is None:
            continue
        if isinstance(attr, property):
            result[key] = attr.__get__(instance)

    return result


_APP = _export_settings(app)
_JWT = _export_settings(jwt)
_DB = _export_settings(db)
_REDIS = _export_settings(redis)
_OSS = _export_settings(oss)
_LLM = _export_settings(llm)
_VLM = _export_settings(vlm)
_OCR = _export_settings(ocr)
_LEAUDIT = _export_settings(_leaudit)

# 将所有变量注入当前模块的全局命名空间
_ALL = {}
_ALL.update(_APP)
_ALL.update(_JWT)
_ALL.update(_DB)
_ALL.update(_REDIS)
_ALL.update(_OSS)
_ALL.update(_LLM)
_ALL.update(_VLM)
_ALL.update(_OCR)
_ALL.update(_LEAUDIT)

globals().update(_ALL)

# 常量
ROOT_PATH = __import__("pathlib").Path(__file__).resolve().parents[2]
