"""
ZIA API — Authentication.

Phase 1: API key via X-API-Key header.
Keys are loaded from ZIA_API_KEYS env var (comma-separated).
Defaults to ["dev-key"] when env var is absent (development mode only).

Phase 2 swap: Replace `verify_api_key` with a JWT/OAuth2 dependency
without touching any route handler.
"""

from __future__ import annotations

import os
from typing import Annotated

from fastapi import Depends, HTTPException, Security, status
from fastapi.security.api_key import APIKeyHeader

_API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)

_DEV_FALLBACK = ["dev-key"]


def _load_api_keys() -> set[str]:
    raw = os.environ.get("ZIA_API_KEYS", "")
    keys = {k.strip() for k in raw.split(",") if k.strip()}
    if not keys:
        import warnings
        warnings.warn(
            "ZIA_API_KEYS not set — using insecure dev-key. "
            "Set ZIA_API_KEYS in production.",
            stacklevel=2,
        )
        return set(_DEV_FALLBACK)
    return keys


# Loaded once at import time; restart server to pick up key changes.
_VALID_KEYS: set[str] = _load_api_keys()


async def verify_api_key(
    api_key: Annotated[str | None, Security(_API_KEY_HEADER)],
) -> str:
    """
    FastAPI dependency. Raises 401 if the API key is missing or invalid.
    Returns the validated key string on success.
    """
    if api_key is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Missing X-API-Key header",
            headers={"WWW-Authenticate": "ApiKey"},
        )
    if api_key not in _VALID_KEYS:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid API key",
        )
    return api_key


# Convenience alias for use in route dependencies
AuthDep = Annotated[str, Depends(verify_api_key)]
