"""Logger module for pypack."""

from __future__ import annotations

import logging

COLORS = {
    "DEBUG": "\033[36m",  # CYAN
    "INFO": "\033[32m",  # GREEN
    "WARNING": "\033[33m",  # YELLOW
    "ERROR": "\033[31m",  # RED
    "CRITICAL": "\033[41m",  # White on Red Background
    "RESET": "\033[0m",  # RESET COLOR
}


class ColoredFormatter(logging.Formatter):
    def format(self, record):
        # 为消息添加颜色
        log_color = COLORS.get(record.levelname, COLORS["RESET"])
        message = super().format(record)
        return f"{log_color}{message}{COLORS['RESET']}"


_logger: logging.Logger | None = None


def get_logger() -> logging.Logger:
    global _logger

    if _logger is None:
        _logger = setup_logger()
    return _logger


def setup_logger() -> logging.Logger:
    logger = logging.getLogger("pytola-pypack")
    logger.setLevel(logging.DEBUG)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    formatter = ColoredFormatter("%(levelname)s - %(message)s")
    console_handler.setFormatter(formatter)

    logger.addHandler(console_handler)
    return logger


logger = get_logger()
