"""HMAC-SHA256 request authentication — thin adapter over textiq_hmac.

Converts a FastAPI Request into a plain dict and delegates all
verification to textiq_hmac.verify_context_headers.

NOTE: This module runs inside the Airflow webserver process which uses
/home/airflow/.local/bin/python — not the project venv. All imports must
be stdlib or packages available in the Airflow base image plus textiq_hmac.
"""

from textiq_hmac import VerificationError, load_key_ring, verify_context_headers


def verify_hmac_headers(request) -> dict:
    """Verify HMAC headers on a FastAPI request.

    Args:
        request: FastAPI Request object.

    Returns:
        dict with keys: tenant_id, node_id, user_id, role

    Raises:
        VerificationError: On any verification failure (maps to HTTP 401).
    """
    # Starlette lowercases all header names, so dict(request.headers) gives
    # {"x-tenant-id": ...} but textiq_hmac does case-sensitive lookups for
    # "X-Tenant-ID", etc. We use request.headers.get() which is case-insensitive,
    # then store each value under the correctly-cased key the library expects.
    header_names = [
        "X-Tenant-ID", "X-Node-ID", "X-User-ID", "X-Role",
        "X-Timestamp", "X-Key-ID", "X-Signature",
    ]
    headers = {}
    for name in header_names:
        value = request.headers.get(name)
        if value:
            headers[name] = value

    key_ring = load_key_ring()
    return verify_context_headers(headers, key_ring)
