"""cortex/api/admin.py — Admin endpoint protection tier (#822).

Provides a ``require_admin`` FastAPI dependency that checks for a separate
admin API key via the ``X-Admin-Key`` header, validated against the
``CORTEX_ADMIN_KEY`` environment variable.

If ``CORTEX_ADMIN_KEY`` is not set, all admin endpoints return 501 Not
Implemented to prevent accidental exposure.
"""

import hmac
import os
from typing import Optional

from fastapi import Header, HTTPException, status


async def require_admin(
    x_admin_key: Optional[str] = Header(None),
) -> None:
    """FastAPI dependency: require admin-level authentication.

    Validates ``X-Admin-Key`` header against ``CORTEX_ADMIN_KEY`` env var.

    Raises:
        HTTPException 501: if ``CORTEX_ADMIN_KEY`` is not configured.
        HTTPException 403: if the key is missing or does not match.
    """
    admin_key = os.environ.get("CORTEX_ADMIN_KEY")
    if not admin_key:
        raise HTTPException(
            status_code=status.HTTP_501_NOT_IMPLEMENTED,
            detail="Admin endpoints are not configured (CORTEX_ADMIN_KEY not set)",
        )
    # Always perform constant-time comparison to prevent timing oracles.
    # Use a dummy value when x_admin_key is None/empty so compare_digest
    # still runs (avoiding short-circuit that leaks key-absence timing).
    key_to_check = x_admin_key if x_admin_key else ""
    key_matches = hmac.compare_digest(key_to_check, admin_key)
    if not x_admin_key or not key_matches:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid or missing X-Admin-Key",
        )
