"""
Logging configuration for real-time output during test execution.
This module ensures logs appear immediately instead of being buffered.
"""
import logging
import sys

LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
DATE_FORMAT = '%H:%M:%S'


def setup_realtime_logging(level=logging.INFO):
    """
    Configure logging for real-time output.
    
    Args:
        level: Logging level (default: INFO)
    """
    formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT)
    root_logger = logging.getLogger()
    root_logger.setLevel(level)
    
    _remove_existing_handlers(root_logger)
    _add_console_handler(root_logger, formatter, level)
    _add_error_handler(root_logger, formatter)
    _suppress_azure_logs()
    
    return root_logger


def _remove_existing_handlers(logger: logging.Logger):
    """Remove existing handlers to avoid duplicates."""
    for handler in logger.handlers[:]:
        logger.removeHandler(handler)


def _add_console_handler(logger: logging.Logger, formatter: logging.Formatter, level: int):
    """Add console handler with real-time output."""
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(level)
    console_handler.setFormatter(formatter)
    console_handler.flush = _create_flush_function(sys.stdout)
    logger.addHandler(console_handler)


def _add_error_handler(logger: logging.Logger, formatter: logging.Formatter):
    """Add error handler for stderr output."""
    error_handler = logging.StreamHandler(sys.stderr)
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    error_handler.flush = _create_flush_function(sys.stderr)
    logger.addHandler(error_handler)


def _create_flush_function(stream):
    """Create a flush function for the given stream."""
    def flush_stream():
        try:
            stream.flush()
        except Exception:
            pass
    return flush_stream

def _suppress_azure_logs():
    """Configure Azure SDK loggers to suppress verbose HTTP request/response logs."""
    azure_loggers = [
        'azure.core.pipeline.policies.http_logging_policy',
        'azure.storage.blob',
        'azure.core.pipeline',
        'urllib3.connectionpool',
        'requests.packages.urllib3.connectionpool',
        'azure.core.pipeline.policies',
        'azure.core.rest'
    ]
    for logger_name in azure_loggers:
        logger = logging.getLogger(logger_name)
        logger.setLevel(logging.WARNING)
        logger.handlers.clear()
        logger.propagate = False


def get_logger(name: str = None):
    """
    Get a logger instance with real-time output.
    
    Args:
        name: Logger name (optional)
    Returns:
        Logger instance
    """
    return logging.getLogger(name)


def _flush_stdout():
    """Force flush stdout to ensure immediate output."""
    try:
        sys.stdout.flush()
    except Exception:
        pass


def _flush_stderr():
    """Force flush stderr to ensure immediate output."""
    try:
        sys.stderr.flush()
    except Exception:
        pass


def log_step(step_number: int, description: str, result: str, logger=None):
    """
    Log a test step with real-time output.
    
    Args:
        step_number: Step number
        description: Step description
        result: Step result (passed/failed/error)
        logger: Logger instance (optional)
    """
    if logger is None or isinstance(logger, str):
        logger = get_logger()
    
    result_lower = result.lower()
    if result_lower in ['passed', 'success', 'ok']:
        logger.info(f"Step {step_number}: {description} - {result}")
    elif result_lower in ['failed', 'error']:
        logger.error(f"Step {step_number}: {description} - {result}")
    else:
        logger.warning(f"Step {step_number}: {description} - {result}")
    
    _flush_stdout()


def log_info(message: str, logger=None):
    """Log info message with real-time output."""
    if logger is None:
        logger = get_logger()
    logger.info(message)
    _flush_stdout()


def log_error(message: str, logger=None):
    """Log error message with real-time output."""
    if logger is None:
        logger = get_logger()
    logger.error(message)
    _flush_stderr()


def log_warning(message: str, logger=None):
    """Log warning message with real-time output."""
    if logger is None:
        logger = get_logger()
    logger.warning(message)
    _flush_stdout()


def log_debug(message: str, logger=None):
    """Log debug message with real-time output."""
    if logger is None:
        logger = get_logger()
    logger.debug(message)
    _flush_stdout()
