"""Token verification and auth header helpers."""
from __future__ import annotations

import os
from typing import Optional

from security.auth.models import Principal


def _extract_bearer(authorization: Optional[str]) -> str:
    if not authorization:
        return ""
    raw = authorization.strip()
    if raw.lower().startswith("bearer "):
        return raw[7:].strip()
    return raw


def verify_internal_service_token(
    authorization: Optional[str] = None,
    x_service_token: Optional[str] = None,
) -> Principal:
    """
    Verify internal service token.

    If AIF_INTERNAL_SERVICE_TOKEN is unset, auth is treated as disabled for local/dev.
    """
    expected = os.getenv("AIF_INTERNAL_SERVICE_TOKEN", "").strip()
    if not expected:
        return Principal(subject="local-dev", auth_type="internal-token", authenticated=True)

    token = _extract_bearer(authorization) or (x_service_token or "").strip()
    if token != expected:
        return Principal(subject="anonymous", auth_type="internal-token", authenticated=False)
    return Principal(subject="service", auth_type="internal-token", authenticated=True)


def build_internal_auth_headers() -> dict[str, str]:
    """Build outbound auth headers for internal service-to-service calls."""
    token = os.getenv("AIF_INTERNAL_SERVICE_TOKEN", "").strip()
    if not token:
        return {}
    return {"Authorization": f"Bearer {token}"}

