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


LOGGER_NAME = "emissary_ml_toolkit"


def get_logger(name: Optional[str] = None) -> logging.Logger:
    """
    Get a logger instance for the toolkit.

    Args:
        name: Optional submodule name (e.g., 'storage', 'train')
              If None, returns the root toolkit logger

    Returns:
        Configured logger instance
    """
    if name:
        return logging.getLogger(f"{LOGGER_NAME}.{name}")
    return logging.getLogger(LOGGER_NAME)


def setup_logging(
    log_file: Optional[Path] = None,
    level: int = logging.INFO,
    format_string: Optional[str] = None,
    include_console: bool = True,
) -> None:
    if format_string is None:
        format_string = (
            "%(asctime)s - %(levelname)s - %(message)s"
        )

    formatter = logging.Formatter(format_string)

    # Get the root logger for the library
    logger = get_logger()
    logger.setLevel(level)

    # Remove existing handlers to avoid duplicate
    logger.handlers.clear()

    # File handler (train.log)
    if log_file:
        log_file = Path(log_file)
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(level)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    if include_console:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(level)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    # Prevent propagation to root logger to avoid duplicate logs
    logger.propagate = False

    logger.info(f"Logging configured - Level: {logging.getLevelName(level)}")


def _setup_default_logger() -> None:
    """
    Setup default logging configuration
    Called automatically when the library is imported
    """
    setup_logging(
        log_file=Path("train.log")
    )
