"""API-key authentication.

The MVP uses a static list of keys loaded from `Settings.api_keys`. This is
deliberate: the service is intended to run on-prem behind an internal
reverse proxy, with a small set of trusted clients (the police HITL UI and
internal automation). Anything more sophisticated (JWT / OAuth / mTLS) is
deferred until there's a concrete need.

When `Settings.api_keys` is empty the dependency permits all requests.
This makes the local dev experience friction-free; production deploys MUST
set at least one key — tested by `test_auth_rejects_missing_key`.
"""

from __future__ import annotations

from typing import Annotated

from fastapi import Header, HTTPException, status

from ocr_sprint.config import get_settings


async def require_api_key(
    x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
) -> None:
    settings = get_settings()
    keys = settings.api_keys_list
    if not keys:
        return  # auth disabled for local dev
    if not x_api_key or x_api_key not in keys:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="invalid or missing API key",
            headers={"WWW-Authenticate": settings.api_key_header},
        )
