"""Structured logging — JSON in production, human-readable locally."""

from __future__ import annotations

import json
import logging
import os
import sys
from datetime import datetime, timezone


class JsonFormatter(logging.Formatter):
    """Produces single-line JSON log entries compatible with Cloud Logging."""

    def format(self, record: logging.LogRecord) -> str:
        entry = {
            "severity": record.levelname,
            "message": record.getMessage(),
            "timestamp": datetime.fromtimestamp(
                record.created, tz=timezone.utc
            ).isoformat(),
            "logger": record.name,
        }
        if record.exc_info and record.exc_info[0] is not None:
            entry["exception"] = self.formatException(record.exc_info)
        return json.dumps(entry, default=str)


def is_production() -> bool:
    """Check if running in a production environment.

    Returns True if K_SERVICE (auto-set by Cloud Run) is present
    or LOOM_ENV is set to 'production'.
    """
    if os.environ.get("K_SERVICE"):
        return True
    return os.environ.get("LOOM_ENV", "").lower() == "production"


def setup_logging(level: str = "INFO") -> None:
    """Configure root logger: JSON in production, human-readable locally."""
    root = logging.getLogger()
    root.setLevel(getattr(logging, level.upper(), logging.INFO))

    # Remove existing handlers to avoid duplicates
    root.handlers.clear()

    handler = logging.StreamHandler(sys.stderr)

    if is_production():
        handler.setFormatter(JsonFormatter())
    else:
        handler.setFormatter(
            logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s")
        )

    root.addHandler(handler)
