# -*- coding: utf-8 -*-
import logging
import os


_LEVEL_MAP = {
    "critical": logging.CRITICAL,
    "error": logging.ERROR,
    "warning": logging.WARNING,
    "info": logging.INFO,
    "debug": logging.DEBUG,
}


class ColorFormatter(logging.Formatter):
    COLORS = {
        logging.DEBUG: "\033[34m",
        logging.INFO: "\033[32m",
        logging.WARNING: "\033[33m",
        logging.ERROR: "\033[31m",
        logging.CRITICAL: "\033[41m\033[97m",
    }
    RESET = "\033[0m"

    def format(self, record):
        color = self.COLORS.get(record.levelno, "")
        level = f"{color}{record.levelname}{self.RESET}"

        full_path = record.pathname
        cwd = os.getcwd()
        if full_path.startswith(cwd):
            full_path = full_path[len(cwd) + 1 :]

        prefix = f"{level} {full_path}:{record.lineno}"
        original_msg = super().format(record)

        return f"{prefix} | {original_msg}"


# Top-level name for this package; only loggers under this name are shown.
LOG_NAMESPACE = "copaw"


def setup_logger(level: int | str = logging.INFO):
    """Configure logging to only output from this package (copaw), not deps."""
    log_format = "%(asctime)s | %(message)s"
    datefmt = "%Y-%m-%d %H:%M:%S"

    if isinstance(level, str):
        level = _LEVEL_MAP.get(level.lower(), logging.INFO)

    formatter = ColorFormatter(log_format, datefmt)

    # Suppress third-party: root has no handler and high level.
    root = logging.getLogger()
    root.setLevel(logging.WARNING)
    root.handlers.clear()

    # Only attach handler to our namespace so only copaw.* logs are printed.
    logger = logging.getLogger(LOG_NAMESPACE)
    logger.setLevel(level)
    logger.propagate = False
    if not logger.handlers:
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    return logger
