import logging
import sys
from datetime import datetime

# Color codes
RESET = "\033[0m"
BOLD = "\033[1m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
GRAY = "\033[90m"

# Color mapping for different log levels
LOG_COLORS = {
    logging.DEBUG: GRAY,
    logging.INFO: CYAN,
    logging.WARNING: YELLOW,
    logging.ERROR: RED,
    logging.CRITICAL: RED + BOLD,
}

class ColoredFormatter(logging.Formatter):
    def __init__(self, fmt=None, datefmt=None):
        super().__init__(fmt, datefmt)
    
    def format(self, record):
        # Get the level color
        level_color = LOG_COLORS.get(record.levelno, WHITE)
        
        # Create colored level name
        levelname = f"{level_color}{record.levelname:8}{RESET}"
        
        # Format time as HH:mm
        time_str = datetime.now().strftime("%H:%M")
        time_formatted = f"{GRAY}{time_str}{RESET}"
        
        # Format origin (logger name)
        origin = f"{BLUE}{record.name}{RESET}"
        
        # Format message
        message = f"{WHITE}{record.getMessage()}{RESET}"
        
        # Construct the final log line
        log_line = f"{time_formatted} {levelname} {origin} → {message}"
        
        # Format exception if present
        if record.exc_info:
            log_line += f"\n{RED}{self.formatException(record.exc_info)}{RESET}"
        
        return log_line

def setup_logger(level=logging.INFO):
    # Create logger
    logger = logging.getLogger()
    logger.setLevel(level)
    
    # Remove existing handlers
    for handler in logger.handlers[:]:
        logger.removeHandler(handler)
    
    # Create console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.DEBUG)
    
    # Create formatter and add it to the handler
    formatter = ColoredFormatter()
    console_handler.setFormatter(formatter)
    
    # Add handler to the logger
    logger.addHandler(console_handler)
    
    return logger

# Example usage
if __name__ == "__main__":
    logger = setup_logger()
    
    # Test different log levels
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")
    logger.critical("This is a critical message")
    
    # Test with different origins
    module_logger = logging.getLogger("my_module")
    module_logger.info("This comes from a specific module")
    
    another_logger = logging.getLogger("another.component")
    another_logger.warning("This comes from another component")