from __future__ import annotations

import os
from typing import Dict, Optional


def resolve_api_key(api_key: Optional[str] = None) -> Optional[str]:
    """Resolve the API key from the explicit parameter or GUNSPEC_API_KEY env var.

    Resolution order:
    1. Explicit ``api_key`` parameter.
    2. ``GUNSPEC_API_KEY`` environment variable.
    3. ``None`` (anonymous / unauthenticated).
    """
    if api_key is not None and api_key != "":
        return api_key
    return os.environ.get("GUNSPEC_API_KEY") or None


def build_auth_headers(api_key: Optional[str] = None) -> Dict[str, str]:
    """Build the authentication headers for a request.

    Returns ``{"X-API-Key": key}`` when a key is available, or an empty dict
    for anonymous mode.
    """
    if api_key is not None and api_key != "":
        return {"X-API-Key": api_key}
    return {}
