"""
Minimal Compass 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"):                    # free tier: prompt your human to subscribe

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

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


class CompassTopUpNeeded(RuntimeError):
    """Raised on HTTP 402 — 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("Compass credits exhausted — subscribe/top up at https://compass.mesa.so/pricing")
    if r.status_code == 401:
        raise RuntimeError("Compass key invalid or revoked")
    r.raise_for_status()
    return r.json()  # check payload.get("sample") to detect free-tier sample data
