"""Device-based authentication middleware.

Instead of traditional signup/login, health apps can identify users by a
stable device UUID. This middleware validates the X-Device-ID header on
protected routes while allowing public endpoints through.
"""
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import JSONResponse, Response

# Paths that do not require device authentication
PUBLIC_PATHS = frozenset({
    "/health",
    "/docs",
    "/redoc",
    "/openapi.json",
})

PUBLIC_PREFIXES = (
    "/api/v1/drugs",
    "/api/v1/supplements",
)


class DeviceAuthMiddleware(BaseHTTPMiddleware):
    """Reject requests to protected endpoints that lack a valid X-Device-ID."""

    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        path = request.url.path

        # Allow public endpoints
        if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES):
            return await call_next(request)

        device_id = request.headers.get("X-Device-ID", "").strip()
        if not device_id:
            return JSONResponse(
                status_code=401,
                content={"detail": "X-Device-ID header is required"},
            )
        if len(device_id) < 8 or len(device_id) > 128:
            return JSONResponse(
                status_code=422,
                content={"detail": "X-Device-ID must be between 8 and 128 characters"},
            )

        return await call_next(request)
