"""Request context middleware — captures client IP and User-Agent per request."""

from contextvars import ContextVar

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

request_ip: ContextVar[str] = ContextVar("request_ip", default="")
request_user_agent: ContextVar[str] = ContextVar("request_user_agent", default="")


def resolve_client_ip(request: Request) -> str:
    """Extract the client IP, honouring ``X-Forwarded-For`` when present."""
    forwarded = request.headers.get("X-Forwarded-For")
    if forwarded:
        return forwarded.split(",")[0].strip()
    if request.client:
        return request.client.host
    return "unknown"


class RequestContextMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        request_ip.set(resolve_client_ip(request))
        request_user_agent.set(request.headers.get("User-Agent", ""))
        return await call_next(request)
