"""Structured logging configuration for the SpherePay MCP server.

Provides JSON and text formatters with automatic correlation ID injection.
See ADR-0014 for rationale.
"""

from __future__ import annotations

import json
import logging
import sys

from spherepay_mcp.domain.context import get_correlation_id


class StructuredFormatter(logging.Formatter):
    """JSON log formatter with correlation ID and structured fields."""

    def format(self, record: logging.LogRecord) -> str:
        entry: dict = {
            "ts": record.created,
            "level": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),
        }
        cid = get_correlation_id()
        if cid:
            entry["correlation_id"] = cid
        extra = getattr(record, "extra", None)
        if extra and isinstance(extra, dict):
            entry.update(extra)
        return json.dumps(entry, default=str)


class TextFormatter(logging.Formatter):
    """Human-readable formatter that includes correlation ID when present."""

    def format(self, record: logging.LogRecord) -> str:
        cid = get_correlation_id()
        cid_str = f" [{cid}]" if cid else ""
        return f"{self.formatTime(record)} {record.levelname}{cid_str} {record.name}: {record.getMessage()}"


def configure_logging(fmt: str = "text", level: str = "INFO") -> None:
    """Configure root logger with the specified format and level.

    Args:
        fmt: "json" for structured JSON output, "text" for human-readable.
        level: Log level string (DEBUG, INFO, WARNING, ERROR).
    """
    root = logging.getLogger()
    root.setLevel(getattr(logging, level.upper(), logging.INFO))

    # Remove existing handlers to avoid duplicates
    for handler in root.handlers[:]:
        root.removeHandler(handler)

    handler = logging.StreamHandler(sys.stderr)
    if fmt == "json":
        handler.setFormatter(StructuredFormatter())
    else:
        handler.setFormatter(TextFormatter())

    root.addHandler(handler)
