"""Authentication helpers (API key + project admin credentials).

All configuration comes from environment variables and is read at request
time so deployments can rotate values without code changes:

* ``API_KEY``                 - when set, every protected route requires the
                                header ``X-API-Key: <API_KEY>``. No other form of
                                authentication is accepted (no bearer tokens, no
                                user sessions). When unset the API stays open
                                (backward compatible) and a warning is logged at
                                startup. ``GET /`` and ``GET /ocr/health`` are
                                always public.
* ``PROJECT_ADMIN_NAME`` /
  ``PROJECT_ADMIN_PASSWORD``  - credentials accepted by /project_init and
                                /project_delete. Fail closed when unset.
* ``ALLOW_PROJECT_DELETE``    - must be truthy for /project_delete to act.
"""

import hmac
import logging
import os
from typing import Annotated

from fastapi import HTTPException, Security
from fastapi.security import APIKeyHeader

logger = logging.getLogger("lvar.security")

_TRUTHY = {"1", "true", "yes", "on"}

# auto_error=False: we raise our own 401 (and skip the check when API_KEY is unset).
_api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)


def _safe_equals(supplied: str, expected: str) -> bool:
    """Constant-time string comparison (handles non-ASCII safely)."""
    return hmac.compare_digest(
        (supplied or "").encode("utf-8"), (expected or "").encode("utf-8")
    )


def api_key_configured() -> bool:
    return bool(os.getenv("API_KEY"))


def require_auth(api_key: Annotated[str | None, Security(_api_key_header)]) -> None:
    """FastAPI dependency: require ``X-API-Key: <API_KEY>`` when env API_KEY is set."""
    expected = os.getenv("API_KEY")
    if not expected:
        return
    if api_key is not None and _safe_equals(api_key, expected):
        return
    raise HTTPException(status_code=401, detail="Not authenticated")


def check_admin_credentials(project_name: str, password: str) -> bool:
    """Compare supplied credentials with env values; fail closed if unset."""
    expected_name = os.getenv("PROJECT_ADMIN_NAME")
    expected_password = os.getenv("PROJECT_ADMIN_PASSWORD")
    if not expected_name or not expected_password:
        return False
    name_ok = _safe_equals(project_name, expected_name)
    password_ok = _safe_equals(password, expected_password)
    return name_ok and password_ok


def project_delete_allowed() -> bool:
    return os.getenv("ALLOW_PROJECT_DELETE", "").strip().lower() in _TRUTHY


def warn_if_insecure() -> None:
    """Log startup warnings for insecure/incomplete configuration."""
    if not api_key_configured():
        logger.warning(
            "API_KEY is not set: all endpoints are accessible without authentication. "
            "Set API_KEY (e.g. in .env) to require an X-API-Key header."
        )
    if not (os.getenv("PROJECT_ADMIN_NAME") and os.getenv("PROJECT_ADMIN_PASSWORD")):
        logger.warning(
            "PROJECT_ADMIN_NAME / PROJECT_ADMIN_PASSWORD not set: "
            "/project_init and /project_delete will refuse all requests."
        )
