"""
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 NAUT_API_KEY in your environment (COMPASS_API_KEY is still read). 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("NAUT_API_BASE") or os.environ.get("COMPASS_API_BASE") or "https://api.naut.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("NAUT_API_KEY") or os.environ.get("COMPASS_API_KEY")
    if not key:
        raise RuntimeError("Set NAUT_API_KEY (mint one at naut.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://naut.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
