from __future__ import annotations

import os
from typing import Any

from fastapi import HTTPException, Request


def _resolve_bearer_token(config: dict[str, Any]) -> str | None:
    http_auth = config.get("http", {}).get("auth", {})
    token = http_auth.get("bearer_token")
    if token:
        return str(token)
    env_token = os.environ.get("NIANNIAN_API_TOKEN")
    return env_token or None


def require_export_auth(request: Request, config: dict[str, Any]) -> None:
    """Enforce bearer token on skill export when http.auth + export_requires_auth are on."""
    http_auth = config.get("http", {}).get("auth", {})
    if not http_auth.get("enabled", False):
        return
    if not config.get("external", {}).get("export_requires_auth", False):
        return

    expected = _resolve_bearer_token(config)
    if not expected:
        raise HTTPException(
            status_code=503,
            detail={"code": "auth_misconfigured", "message": "http.auth.enabled but no bearer token"},
        )

    auth_header = request.headers.get("Authorization", "")
    if not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail={"code": "unauthorized"})
    if auth_header[7:].strip() != expected:
        raise HTTPException(status_code=401, detail={"code": "unauthorized"})
