"""
Django middleware for OpenTelemetry trace context.
"""
import logging

from opentelemetry import context
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

logger = logging.getLogger(__name__)

_propagator = TraceContextTextMapPropagator()


class TraceContextMiddleware:
    """
    Extracts trace context from incoming request headers (traceparent) and attaches
    it so downstream spans and logs are correlated with the upstream trace.
    Place after AuthenticationMiddleware so user is available for logging.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        token = None
        traceparent = request.headers.get("traceparent") or request.META.get(
            "HTTP_TRACEPARENT"
        )
        if traceparent:
            try:
                carrier = {"traceparent": traceparent}
                ctx = _propagator.extract(carrier=carrier)
                token = context.attach(ctx)
            except Exception as e:
                logger.debug("Failed to extract trace context: %s", e)

        try:
            return self.get_response(request)
        finally:
            if token is not None:
                try:
                    context.detach(token)
                except Exception:
                    pass
