import logging
import os

from bubobot_mcp.src.config.config import Config


def setup_logging(config: Config, log_level: int = logging.DEBUG) -> None:
    """
    Setup a logging system that can log to both console and file.
    
    Args:
        config (Config): Configuration object containing logging settings
        log_level (int): Logging level for all handlers (default: DEBUG)
    
    Returns:
        None
    """
    # Create log directory if it doesn't exist
    os.makedirs(config.log_dir, exist_ok=True)

    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(log_level)

    # Create formatter for consistent log message format
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

    # Add console handler if not already present
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_handler.setFormatter(formatter)
    if not any(isinstance(h, logging.StreamHandler) for h in root_logger.handlers):
        root_logger.addHandler(console_handler)

    # Add file handler if logging to file is enabled
    if config.save_log:
        file_handler = logging.FileHandler(
            os.path.join(config.log_dir, "mcp_server.log"), 
            encoding='utf-8'
        )
        file_handler.setLevel(log_level)
        file_handler.setFormatter(formatter)
        if not any(isinstance(h, logging.FileHandler) for h in root_logger.handlers):
            root_logger.addHandler(file_handler)
