"""日志模块 —— 通道由调用栈自动推断。"""

from __future__ import annotations

import logging
import sys


def _infer_channel() -> str:
    """根据调用栈自动推断日志通道。"""
    frame = sys._getframe(2)
    filename = frame.f_code.co_filename
    if "/controllers/" in filename:
        return "CONTROLLER"
    if "/services/" in filename:
        return "SERVICE"
    if "/models/" in filename:
        return "MODEL"
    if "/leaudit_bridge/" in filename:
        return "BRIDGE"
    if "/handler/" in filename:
        return "HANDLER"
    if "/tasks/" in filename:
        return "TASK"
    if "/middleware/" in filename:
        return "MIDDLEWARE"
    if "postgrest" in filename:
        return "POSTGREST"
    if "uvicorn" in filename:
        return "UVICORN"
    return "APP"


class _ChannelLogger:
    """代理 logger，自动推断通道。"""

    def __getattr__(self, name: str):
        channel = _infer_channel()
        logger = logging.getLogger(channel)
        return getattr(logger, name)


logger: object = _ChannelLogger()  # type: ignore[assignment]
