"""Logger module for pytola."""

from __future__ import annotations

import logging
from typing import ClassVar


class ColoredLogger:
    _instance: logging.Logger | None = None

    COLORS: ClassVar[dict[str, str]] = {
        "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
    }

    @staticmethod
    def get_logger(name: str = "pytola") -> logging.Logger:
        if ColoredLogger._instance is None:
            ColoredLogger._instance = ColoredLogger.setup_logger(name)

        return ColoredLogger._instance

    @classmethod
    def setup_logger(cls, name: str) -> logging.Logger:

        class _ColoredFormatter(logging.Formatter):
            def format(self, record):
                log_color = ColoredLogger.COLORS.get(record.levelname, ColoredLogger.COLORS["RESET"])
                message = super().format(record)
                return f"{log_color}{message}{ColoredLogger.COLORS['RESET']}"

        logger = logging.getLogger(name)
        logger.setLevel(logging.INFO)

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

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

        logger.addHandler(console_handler)
        return logger


get_logger = ColoredLogger.get_logger
logger = ColoredLogger.get_logger()
