"""Per-process file logging for MCube services (webhook, ws_bridge, ai_worker)."""

from __future__ import annotations

import logging
import os
from pathlib import Path

_COMPONENT_LOGGER = {
    "webhook": "mcube.webhook",
    "ws_bridge": "mcube.ws_bridge",
    "ai_worker": "mcube.ai_worker",
}


def configure_mcube_file_logging(component: str) -> None:
    """
    Attach a FileHandler to the component logger so logs survive container restarts when a volume
    is mounted at MCUBE_LOG_DIR.

    Env:
      MCUBE_LOG_DIR — base directory (default /tmp/mcube_logs)
      MCUBE_SERVICE_LOG_DISABLE=1 — skip file handler
    """
    if os.getenv("MCUBE_SERVICE_LOG_DISABLE", "").strip().lower() in ("1", "true", "yes"):
        return

    logger_name = _COMPONENT_LOGGER.get(component, f"mcube.{component}")
    lg = logging.getLogger(logger_name)

    for h in lg.handlers:
        if getattr(h, "_mcube_service_file", False):
            return

    base = os.getenv("MCUBE_LOG_DIR", "").strip() or "/tmp/mcube_logs"
    Path(base).mkdir(parents=True, exist_ok=True)
    path = Path(base) / f"{component}.log"

    fh = logging.FileHandler(path, encoding="utf-8")
    fh._mcube_service_file = True  # type: ignore[attr-defined]
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(
        logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
    )
    lg.addHandler(fh)
    # Ensure messages propagate if root level allows
    lg.setLevel(logging.DEBUG)