"""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)

# """Rotating file logs for MCube long-running processes (ws_bridge, ai_worker, webhook_server)."""

# from __future__ import annotations

# import logging
# import os
# from logging.handlers import RotatingFileHandler
# from pathlib import Path

# _AGENT_RUNTIME_ROOT = Path(__file__).resolve().parent.parent.parent


# def configure_mcube_file_logging(service_name: str) -> None:
#     """
#     Append INFO+ logs to ``agent_runtime/logs/mcube_<service>.log`` (5 MB x 3 rotations).

#     Disable with ``MCUBE_FILE_LOG_DISABLE=1``.
#     """
#     if os.getenv("MCUBE_FILE_LOG_DISABLE", "").strip().lower() in ("1", "true", "yes"):
#         return

#     log_dir = _AGENT_RUNTIME_ROOT / "logs"
#     log_dir.mkdir(parents=True, exist_ok=True)
#     path = log_dir / f"mcube_{service_name}.log"

#     fh = RotatingFileHandler(str(path), maxBytes=5_000_000, backupCount=3, encoding="utf-8")
#     fh.setLevel(logging.INFO)
#     fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))

#     root = logging.getLogger()
#     tag = f"mcube_rotating_{service_name}"
#     for h in root.handlers:
#         if getattr(h, "_mcube_rotating_tag", None) == tag:
#             return
#     fh._mcube_rotating_tag = tag  # type: ignore[attr-defined]
#     root.addHandler(fh)
#     if root.level > logging.INFO:
#         root.setLevel(logging.INFO)
