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

    from naut_fetch import naut, NautApiError
    me = naut("/me")                            # free: identity + sampleMode
    people = naut("/people?q=defi&limit=10")
    if people.get("sample"):                    # free plan: tell your human the rows are synthetic

Set NAUT_API_KEY in your environment (COMPASS_API_KEY is still read). A free account's key returns marked samples
(payload["sample"] is True) whatever its balance; a key on a trial or paid plan returns live data billed in credits;
a paid key that runs out gets a 402.

A failed call raises NautApiError carrying status, code, hint and, on a trial's daily limit, next_at:
    402                        balance empty: ask your human to upgrade the plan (raised as NautTopUpNeeded)
    429 TRIAL_DAILY_LIMIT      trial past today's share: wait until next_at, or start the plan now
    403 UNPAID_PLAN            private reveal before the plan is paid: start it in Settings > Plan & billing
    410 HOST_RETIRED           old host: use https://api.naut.so
"""
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 NautApiError(RuntimeError):
    """Raised on any non-2xx response, with the API's error code and hint."""

    def __init__(self, status: int, error: dict):
        self.status = status
        self.code = error.get("code")
        self.hint = error.get("hint")
        self.next_at = error.get("nextAt")
        self.error = error
        label = f" {self.code}" if self.code else ""
        super().__init__(f"NAUT {status}{label}: {self.hint or error.get('message') or 'request failed'}")


class NautTopUpNeeded(NautApiError):
    """Raised on HTTP 402: the credit balance is empty."""


def naut(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 (create one at https://naut.so/developer)")
    r = requests.get(f"{BASE}{path}", headers={"Authorization": f"Bearer {key}"}, timeout=30)
    if not r.ok:
        try:
            body = r.json()
        except ValueError:
            body = {}
        error = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), dict) else {}
        if r.status_code == 402:
            raise NautTopUpNeeded(r.status_code, error)
        raise NautApiError(r.status_code, error)
    return r.json()  # check payload.get("sample") to detect free-plan sample data


# The names this helper had as compass_fetch.py, kept so older code keeps working.
compass = naut
CompassTopUpNeeded = NautTopUpNeeded
