"""
Centralized logging configuration with colors and timestamps.

This module configures logging for the entire application with:
- Colored output for different log levels
- Timestamps in ISO format
- Structured log format with module names
- Different colors for different log levels
"""

import logging
import sys
from typing import Optional


# ANSI color codes for terminal output
class LogColors:
    """ANSI color codes for terminal output."""
    RESET = '\033[0m'
    BOLD = '\033[1m'
    
    # Log level colors
    DEBUG = '\033[36m'      # Cyan
    INFO = '\033[32m'       # Green
    WARNING = '\033[33m'    # Yellow
    ERROR = '\033[31m'      # Red
    CRITICAL = '\033[35m'   # Magenta
    
    # Component colors
    TIMESTAMP = '\033[90m'  # Gray
    MODULE = '\033[94m'     # Blue
    MESSAGE = '\033[0m'     # Default


class ColoredFormatter(logging.Formatter):
    """Custom formatter that adds colors to log messages."""
    
    # Format template
    FORMAT_TEMPLATE = (
        "%(color_timestamp)s%(asctime)s%(reset)s | "
        "%(color_level)s%(levelname)-8s%(reset)s | "
        "%(color_module)s%(name)s%(reset)s | "
        "%(color_message)s%(message)s%(reset)s"
    )
    
    # Map log levels to colors
    LEVEL_COLORS = {
        logging.DEBUG: LogColors.DEBUG,
        logging.INFO: LogColors.INFO,
        logging.WARNING: LogColors.WARNING,
        logging.ERROR: LogColors.ERROR,
        logging.CRITICAL: LogColors.CRITICAL,
    }
    
    def __init__(self, use_colors: bool = True):
        """
        Initialize the formatter.
        
        Args:
            use_colors: Whether to use colored output (default: True)
        """
        super().__init__(
            fmt=self.FORMAT_TEMPLATE,
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        self.use_colors = use_colors
    
    def format(self, record: logging.LogRecord) -> str:
        """Format the log record with colors."""
        if self.use_colors and sys.stderr.isatty():
            # Add color codes to the record
            record.color_timestamp = LogColors.TIMESTAMP
            record.color_level = self.LEVEL_COLORS.get(record.levelno, LogColors.RESET)
            record.color_module = LogColors.MODULE
            record.color_message = LogColors.MESSAGE
            record.reset = LogColors.RESET
        else:
            # No colors (for file output or non-TTY)
            record.color_timestamp = ''
            record.color_level = ''
            record.color_module = ''
            record.color_message = ''
            record.reset = ''
        
        return super().format(record)


def setup_logging(
    level: int = logging.INFO,
    use_colors: bool = True,
    log_file: Optional[str] = None
) -> None:
    """
    Setup logging configuration for the entire application.
    
    Args:
        level: Logging level (default: logging.INFO)
        use_colors: Whether to use colored output for console (default: True)
        log_file: Optional path to log file (default: None, logs to console only)
    
    Example:
        >>> from app.logging_config import setup_logging
        >>> setup_logging(level=logging.DEBUG, log_file="app.log")
    """
    # Get root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(level)
    
    # Remove existing handlers to avoid duplicates
    root_logger.handlers.clear()
    
    # Console handler with colors
    console_handler = logging.StreamHandler(sys.stderr)
    console_handler.setLevel(level)
    console_handler.setFormatter(ColoredFormatter(use_colors=use_colors))
    root_logger.addHandler(console_handler)
    
    # File handler without colors (if specified)
    if log_file:
        file_handler = logging.FileHandler(log_file, mode='a', encoding='utf-8')
        file_handler.setLevel(level)
        file_handler.setFormatter(ColoredFormatter(use_colors=False))
        root_logger.addHandler(file_handler)
    
    # Reduce noise from third-party libraries
    logging.getLogger('httpx').setLevel(logging.WARNING)
    logging.getLogger('httpcore').setLevel(logging.WARNING)
    logging.getLogger('urllib3').setLevel(logging.WARNING)
    logging.getLogger('sqlalchemy').setLevel(logging.WARNING)
    
    # Log startup message
    logger = logging.getLogger(__name__)
    logger.info("🚀 Logging initialized with colored output and timestamps")
    if log_file:
        logger.info(f"📝 Logging to file: {log_file}")


# Convenience function to get a logger with standard formatting
def get_logger(name: str) -> logging.Logger:
    """
    Get a logger instance with the module name.
    
    Args:
        name: Logger name (typically __name__)
    
    Returns:
        Configured logger instance
    
    Example:
        >>> from app.logging_config import get_logger
        >>> logger = get_logger(__name__)
        >>> logger.info("This is a colored log message")
    """
    return logging.getLogger(name)
