"""
Minimal NAUT API helper (stdlib + requests, no SDK needed).

    from compass_fetch import compass, CompassTopUpNeeded
    me = compass("/me")                         # free: identity + sampleMode
    people = compass("/people?q=defi&limit=10")
    if people.get("sample"):                    # insufficient credits: prompt your human to top up

Set COMPASS_API_KEY in your environment. A key with too few credits returns marked
samples (payload["sample"] is True); a key with enough credits returns live data billed in credits.
"""
import os
import requests

BASE = os.environ.get("COMPASS_API_BASE", "https://api.compass.mesa.so/v1")


class CompassTopUpNeeded(RuntimeError):
    """Raised on HTTP 402: the paid credit balance is empty."""


def compass(path: str, key: str | None = None) -> dict:
    key = key or os.environ.get("COMPASS_API_KEY")
    if not key:
        raise RuntimeError("Set COMPASS_API_KEY (mint one at compass.mesa.so > Settings > API)")
    r = requests.get(f"{BASE}{path}", headers={"Authorization": f"Bearer {key}"})
    if r.status_code == 402:
        raise CompassTopUpNeeded("NAUT credits exhausted: subscribe or top up at https://compass.mesa.so/pricing")
    if r.status_code == 401:
        raise RuntimeError("NAUT key invalid or revoked")
    r.raise_for_status()
    return r.json()  # check payload.get("sample") to detect insufficient-credit sample data
