"""
Logging utilities for health checker.
"""

import logging
import logging.handlers
import sys
from pathlib import Path
from typing import Optional


def setup_logging(
    level: str = "INFO",
    log_file: Optional[str] = None,
    max_bytes: int = 10 * 1024 * 1024,  # 10MB
    backup_count: int = 5,
    format_string: Optional[str] = None
) -> None:
    """
    Setup logging configuration for health checker.
    
    Args:
        level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        log_file: Optional log file path
        max_bytes: Maximum log file size in bytes before rotation
        backup_count: Number of backup log files to keep
        format_string: Custom log format string
    """
    # Default format
    if format_string is None:
        format_string = (
            "%(asctime)s - %(name)s - %(levelname)s - "
            "%(filename)s:%(lineno)d - %(message)s"
        )
    
    formatter = logging.Formatter(format_string)
    
    # Get root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, level.upper()))
    
    # Clear existing handlers
    root_logger.handlers.clear()
    
    # Console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    
    # File handler if log file is specified
    if log_file:
        log_path = Path(log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        
        file_handler = logging.handlers.RotatingFileHandler(
            log_file,
            maxBytes=max_bytes,
            backupCount=backup_count,
            encoding='utf-8'
        )
        file_handler.setFormatter(formatter)
        root_logger.addHandler(file_handler)
    
    # Set specific logger levels for noisy modules
    logging.getLogger('requests').setLevel(logging.WARNING)
    logging.getLogger('urllib3').setLevel(logging.WARNING)


def get_logger(name: str) -> logging.Logger:
    """
    Get a logger instance with the specified name.
    
    Args:
        name: Logger name
        
    Returns:
        Logger instance
    """
    return logging.getLogger(name)


class HealthCheckLoggerAdapter(logging.LoggerAdapter):
    """Logger adapter that adds context to health check log messages."""
    
    def __init__(self, logger: logging.Logger, extra: dict):
        """
        Initialize logger adapter.
        
        Args:
            logger: Base logger instance
            extra: Extra context dictionary
        """
        super().__init__(logger, extra)
    
    def process(self, msg, kwargs):
        """Add context to log message."""
        if 'extra' not in kwargs:
            kwargs['extra'] = {}
        
        # Add our context to the extra dict
        kwargs['extra'].update(self.extra)
        
        return msg, kwargs


def get_service_logger(service_name: str) -> logging.LoggerAdapter:
    """
    Get a logger adapter specific to a service.
    
    Args:
        service_name: Name of the service
        
    Returns:
        Service-specific logger adapter
    """
    logger = logging.getLogger(f'openHealth.service.{service_name}')
    return HealthCheckLoggerAdapter(
        logger,
        {'service_name': service_name}
    )