"""Auth helpers for Armorer web API."""

from __future__ import annotations

import os

from fastapi import Header, HTTPException, status

from armorer.config import resolve_armorer_config_dir


TOKEN_ENV_NAME = "ARMORER_UI_API_TOKEN"
TOKEN_HEADER_NAME = "X-ARMORER-UI-TOKEN"


def _resolve_expected_ui_token() -> str:
    expected = str(os.getenv(TOKEN_ENV_NAME) or "").strip()
    if expected:
        return expected

    token_path = resolve_armorer_config_dir() / "ui-api-token"
    try:
        return token_path.read_text(encoding="utf-8").strip()
    except Exception:
        return ""


def require_ui_token(x_armorer_ui_token: str | None = Header(default=None)) -> None:
    expected = _resolve_expected_ui_token()
    if not expected:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"{TOKEN_ENV_NAME} is not configured on the server.",
        )
    provided = str(x_armorer_ui_token or "").strip()
    if provided != expected:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API token.",
        )
