"""Structured logging for the launcher."""

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


_configured = False


def setup_logging(level: str = "INFO", log_dir: Optional[Path] = None) -> None:
    """Configure logging for the launcher."""
    global _configured
    if _configured:
        return
    _configured = True

    root = logging.getLogger("mercury_launcher")
    root.setLevel(getattr(logging, level.upper(), logging.INFO))

    # Console handler
    console = logging.StreamHandler(sys.stderr)
    console.setFormatter(logging.Formatter(
        "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        datefmt="%H:%M:%S",
    ))
    root.addHandler(console)

    # Optional file handler per-agent (set up later via get_agent_logger)
    if log_dir:
        log_dir.mkdir(parents=True, exist_ok=True)


def get_logger(name: str) -> logging.Logger:
    """Get a logger under the mercury_launcher namespace."""
    return logging.getLogger(f"mercury_launcher.{name}")
