"""
Request ID middleware.

Generates a unique ID per incoming request and:
1. Sets it in the request_id context var so every log line emitted
   while handling this request is automatically tagged with it.
2. Echoes it back in the X-Request-ID response header, so if the client
   reports "my request failed", they can give you the exact ID to grep
   in logs instead of "it failed around 3pm sometime."
"""

import time
import uuid

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response

from app.core.logging_config import get_logger, request_id_ctx

logger = get_logger("app.request")


class RequestContextMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next) -> Response:
        request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
        token = request_id_ctx.set(request_id)
        start = time.perf_counter()

        try:
            response = await call_next(request)
        finally:
            request_id_ctx.reset(token)

        elapsed_ms = int((time.perf_counter() - start) * 1000)
        response.headers["X-Request-ID"] = request_id
        logger.info(
            f"{request.method} {request.url.path} -> {response.status_code} ({elapsed_ms}ms)"
        )
        return response
