import logging
import sys
from loguru import logger as loguru_logger


class InterceptHandler(logging.Handler):
    def emit(self, record):
        # 获取对应的Loguru日志级别
        try:
            level = loguru_logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # 查找日志来源
        frame, depth = logging.currentframe(), 2
        while frame and frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        # 使用Loguru记录日志
        loguru_logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())


def setup_logging():
    # 拦截标准logging
    logging.basicConfig(handlers=[InterceptHandler()], level=logging.NOTSET)

    # 移除所有现有处理器
    loguru_logger.remove()

    # 添加新的处理器
    loguru_logger.add(
        sys.stdout,
        format=(
            "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
            "<level>{message}</level>"
        ),
        level="DEBUG",
        enqueue=True
    )

    # 添加文件日志
    loguru_logger.add(
        "app.log",
        rotation="10 MB",
        retention="30 days",
        level="INFO",
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {message}"
    )


# 创建通用logger接口
class Logger:
    @staticmethod
    def debug(msg, *args, **kwargs):
        loguru_logger.debug(msg, *args, **kwargs)

    @staticmethod
    def info(msg, *args, **kwargs):
        loguru_logger.info(msg, *args, **kwargs)

    @staticmethod
    def warning(msg, *args, **kwargs):
        loguru_logger.warning(msg, *args, **kwargs)

    @staticmethod
    def error(msg, *args, **kwargs):
        loguru_logger.error(msg, *args, **kwargs)

    @staticmethod
    def critical(msg, *args, **kwargs):
        loguru_logger.critical(msg, *args, **kwargs)

    @staticmethod
    def exception(msg, *args, **kwargs):
        loguru_logger.exception(msg, *args, **kwargs)

    @staticmethod
    def success(msg, *args, **kwargs):
        loguru_logger.success(msg, *args, **kwargs)


# 创建全局logger实例
logger = Logger()

# 初始化日志系统
setup_logging()