import logging

from loguru import logger

from algo_backend.config import LoguruConfig

disable_log_pkg = LoguruConfig.get_disable_log_pkg()


def patch_logging_to_loguru():
    """
    将 Python 原生 logging 系统的所有日志重定向到 loguru
    """

    class LoguruHandler(logging.Handler):
        def emit(self, record):
            # 过滤特定模块的日志
            if any(excluded in record.name for excluded in disable_log_pkg):
                return

            try:
                level = logger.level(record.levelname).name
            except ValueError:
                level = record.levelno

            # 从当前帧开始，找到真正调用 logging 的位置
            frame = logging.currentframe()
            depth = 0  # 从0开始计算，动态确定深度

            # 遍历调用栈，跳过所有 logging 模块的内部调用
            while frame:
                filename = frame.f_code.co_filename
                func_name = frame.f_code.co_name

                # 检查是否为 logging 模块的内部调用
                is_logging_internal = (
                    # 标准库 logging 模块路径
                    "logging" in filename
                    and (
                        filename.endswith("logging/__init__.py")
                        or "/logging/" in filename
                        or "\\logging\\" in filename
                    )
                ) or (
                    # logging 内部函数名
                    func_name
                    in (
                        "callHandlers",
                        "handle",
                        "emit",
                        "handleError",
                        "_log",
                        "makeRecord",
                        "getLogger",
                        "debug",
                        "info",
                        "warning",
                        "error",
                        "exception",
                        "critical",
                    )
                )

                if is_logging_internal:
                    frame = frame.f_back
                    depth += 1
                else:
                    # 找到真实的调用者，跳出循环
                    break

            # 如果找不到合适的帧，回退到默认行为
            if not frame:
                depth = 2

            logger.opt(depth=depth, exception=record.exc_info).log(
                level, record.getMessage()
            )

    # 设置根记录器级别为最低级别，确保所有日志都被处理
    logging.root.setLevel(logging.DEBUG)

    logging.root.handlers = []
    logging.root.addHandler(LoguruHandler())
