"""Request-scoped context for structured logging.

Binds a unique request ID to structlog's contextvars so every log line
emitted during a request (including foreign stdlib loggers from sam2_onnx)
carries the same ``request_id``.

Usage — server (FastAPI / ASGI middleware)::

    async def middleware(request, call_next):
        bind_request_id()          # auto UUID4
        try:
            return await call_next(request)
        finally:
            clear_request_context()

Usage — desktop (QGIS plugin task)::

    rid = bind_request_id()
    try:
        predictor.set_image(img)
        masks = predictor.predict(...)
    finally:
        clear_request_context()
"""

from uuid import uuid4

import structlog


def bind_request_id(request_id: str | None = None) -> str:
    """Bind a *request_id* to the current structlog context.

    If *request_id* is ``None``, a new UUID4 is generated.
    Returns the (possibly generated) request ID.
    """
    if request_id is None:
        request_id = uuid4().hex
    structlog.contextvars.bind_contextvars(request_id=request_id)
    return request_id


def clear_request_context() -> None:
    """Remove all request-scoped keys from the structlog context."""
    structlog.contextvars.clear_contextvars()
