"""
Logging configuration for pypabhiveagent package.

This module provides centralized logging configuration with:
- Configurable log levels
- Formatted output with timestamps
- Sensitive information filtering
- Console and file logging support
"""

import logging
import sys
from typing import Optional


class SensitiveDataFilter(logging.Filter):
    """
    Filter to prevent logging of sensitive information like tokens and passwords.
    """
    
    SENSITIVE_KEYS = ['token', 'password', 'hive_password', 'passwd', 'secret', 'api_key']
    
    def filter(self, record: logging.LogRecord) -> bool:
        """
        Filter log records to mask sensitive data.
        
        Args:
            record: Log record to filter
            
        Returns:
            bool: Always True (we modify but don't block records)
        """
        # Mask sensitive data in the message
        if hasattr(record, 'msg') and isinstance(record.msg, str):
            message = record.msg
            for key in self.SENSITIVE_KEYS:
                # Replace patterns like "token=abc123" or "token: abc123"
                if key in message.lower():
                    # Simple masking - replace the value after the key
                    import re
                    # Pattern: key followed by = or : and then the value
                    pattern = rf"({key}[=:\s]+)([^\s,\)}}]+)"
                    message = re.sub(pattern, r"\1***MASKED***", message, flags=re.IGNORECASE)
            record.msg = message
        
        return True


def configure_logging(
    level: str = 'INFO',
    log_file: Optional[str] = None,
    format_string: Optional[str] = None,
    enable_sensitive_filter: bool = True
) -> None:
    """
    Configure logging for pypabhiveagent package.
    
    Args:
        level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        log_file: Optional file path for file logging
        format_string: Optional custom format string
        enable_sensitive_filter: Whether to enable sensitive data filtering (default: True)
    
    Example:
        >>> from pypabhiveagent.logging_config import configure_logging
        >>> configure_logging(level='DEBUG', log_file='pypabhiveagent.log')
    """
    # Convert string level to logging constant
    numeric_level = getattr(logging, level.upper(), logging.INFO)
    
    # Default format string with timestamp, level, module, and message
    if format_string is None:
        format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    
    # Create formatter
    formatter = logging.Formatter(format_string, datefmt='%Y-%m-%d %H:%M:%S')
    
    # Get the root logger for pypabhiveagent
    logger = logging.getLogger('pypabhiveagent')
    logger.setLevel(numeric_level)
    
    # Remove existing handlers to avoid duplicates
    logger.handlers.clear()
    
    # Console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(numeric_level)
    console_handler.setFormatter(formatter)
    
    # Add sensitive data filter if enabled
    if enable_sensitive_filter:
        console_handler.addFilter(SensitiveDataFilter())
    
    logger.addHandler(console_handler)
    
    # File handler (optional)
    if log_file:
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(numeric_level)
        file_handler.setFormatter(formatter)
        
        # Add sensitive data filter if enabled
        if enable_sensitive_filter:
            file_handler.addFilter(SensitiveDataFilter())
        
        logger.addHandler(file_handler)
    
    # Prevent propagation to root logger to avoid duplicate logs
    logger.propagate = False
    
    logger.debug(f"Logging configured: level={level}, file={log_file}")


def get_logger(name: str) -> logging.Logger:
    """
    Get a logger instance for a specific module.
    
    Args:
        name: Logger name (typically __name__ of the module)
        
    Returns:
        logging.Logger: Logger instance
    
    Example:
        >>> from pypabhiveagent.logging_config import get_logger
        >>> logger = get_logger(__name__)
        >>> logger.info("This is a log message")
    """
    # Ensure the logger is under pypabhiveagent namespace
    if not name.startswith('pypabhiveagent'):
        name = f'pypabhiveagent.{name}'
    
    return logging.getLogger(name)


def set_log_level(level: str) -> None:
    """
    Change the logging level at runtime.
    
    Args:
        level: New logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
    
    Example:
        >>> from pypabhiveagent.logging_config import set_log_level
        >>> set_log_level('DEBUG')
    """
    numeric_level = getattr(logging, level.upper(), logging.INFO)
    logger = logging.getLogger('pypabhiveagent')
    logger.setLevel(numeric_level)
    
    # Update all handlers
    for handler in logger.handlers:
        handler.setLevel(numeric_level)
    
    logger.debug(f"Log level changed to: {level}")


# Configure default logging when module is imported
# Users can reconfigure by calling configure_logging()
configure_logging(level='INFO')
