"""Structured JSON logging via structlog."""
from __future__ import annotations

import logging
import sys
from contextvars import ContextVar
from typing import Any

import structlog

_job_run_id: ContextVar[str] = ContextVar("job_run_id", default="")


def bind_job_run_id(run_id: str) -> None:
    _job_run_id.set(run_id)


def _add_job_run_id(
    logger: Any, method: str, event_dict: dict[str, Any]
) -> dict[str, Any]:
    run_id = _job_run_id.get()
    if run_id:
        event_dict["job_run_id"] = run_id
    return event_dict


def configure_logging(level: str = "INFO") -> None:
    logging.basicConfig(
        format="%(message)s",
        stream=sys.stdout,
        level=getattr(logging, level.upper(), logging.INFO),
    )

    structlog.configure(
        processors=[
            structlog.contextvars.merge_contextvars,
            _add_job_run_id,
            structlog.stdlib.add_log_level,
            structlog.processors.TimeStamper(fmt="iso"),
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.processors.JSONRenderer(),
        ],
        wrapper_class=structlog.make_filtering_bound_logger(
            getattr(logging, level.upper(), logging.INFO)
        ),
        context_class=dict,
        logger_factory=structlog.PrintLoggerFactory(),
        cache_logger_on_first_use=False,
    )


def get_logger(name: str = "") -> structlog.BoundLogger:
    return structlog.get_logger(name)
