from __future__ import annotations

import logging
from pathlib import Path
from typing import Optional

from .settings import LoggingSettings

_LOGGER_ROOT = "keiro.gateway"


def configure_gateway_logging(log_settings: LoggingSettings) -> Optional[Path]:
    """Ensure gateway loggers write to the configured file handler.

    Returns the resolved log path when logging is enabled, otherwise ``None``.
    """
    if not log_settings.enabled:
        return None

    level_name = (log_settings.level or "INFO").upper()
    level = getattr(logging, level_name, logging.INFO)

    logger = logging.getLogger(_LOGGER_ROOT)
    logger.setLevel(level)

    if not log_settings.path:
        return None

    target_path = Path(log_settings.path).expanduser()
    target_path.parent.mkdir(parents=True, exist_ok=True)

    # Reuse existing handler when already configured for this path.
    for handler in logger.handlers:
        if isinstance(handler, logging.FileHandler):
            try:
                existing = Path(handler.baseFilename).resolve()
            except OSError:
                continue
            if existing == target_path.resolve():
                handler.setLevel(level)
                return target_path

    formatter = logging.Formatter(
        "%(asctime)s %(levelname)s %(name)s: %(message)s"
    )
    file_handler = logging.FileHandler(target_path)
    file_handler.setLevel(level)
    file_handler.setFormatter(formatter)

    logger.addHandler(file_handler)
    logger.propagate = True

    return target_path


__all__ = ["configure_gateway_logging"]
