#!/usr/bin/env python3
"""tn-api: read Terminal data with a read-only API key (https://api.tribulnation.com/docs).

  tn-api PATH [NAME=VALUE ...] [--trim N] [--compact] [--raw]

  tn-api /me/portfolio from=2026-11-10
  tn-api /live/opportunities --trim 5
  tn-api /live/book/bitcoin depth=5
  tn-api /live/profile asset=bitcoin venue=hyperliquid market=BTC window=7d
  tn-api /v1/market/perps/funding/historical assets=bitcoin venues=binance from=2026-10-01 to=2026-10-02
  tn-api /api/market/charts/history asset=bitcoin exchanges=hyperliquid:,binance:usdm series=index,mark range=7d

The key: TN_API_KEY (tn_key_ and 43 characters, made on <app>/integrations, read-only;
me:read for your own data, market:read on Ultra for market data), else the key
`tn terminal auth login` saved (~/.config/tn/terminal.json, mode 600), which is only
sent to the host that issued it and that host's app. The PATH picks the server:

  /me, /me/..., /v1/..., /v2/..., /live/...
                 the API host: $TN_API_BASE, else the saved login's host, else
                 https://api.tribulnation.com. /api/live/... is read there as /live/...
                 (the app's /api/live is for its own pages).
  /api/...       the app, for the market routes the API host does not serve yet: index
                 and mark history and the Charts series (/api/market/...),
                 /api/charts/venues, /api/opportunities/rows and counts, /api/search,
                 /api/asset-candles, /api/asset-section, /api/tracking/fx (market:read,
                 Ultra), and your own data's app routes (me:read). Server
                 $TERMINAL_BASE_URL, else the API host's app (api.X -> app.X; a host
                 with a port -> the same host without it).

GET only (no key can do anything else). TN_API_KEY comes from
the environment, else from the env file $TERMINAL_AGENT_ENV (default
~/.config/terminal/agent.env, lines NAME=value). The key is sent in the Authorization
header from inside this process: never on a command line, never printed, and scrubbed
from any error body echoed. The server must be https (plain http only to localhost), and
a redirect is refused rather than followed, so the key only ever goes to that origin.

Output: the JSON answer, pretty-printed (--compact: one line; --raw: as received).
--trim N keeps the first N items of every list (the arrays can be long); how many it
cut goes to stderr, so stdout stays clean JSON for jq. When the portfolio answer is the
stored fallback (header X-Portfolio-Last-Answer), a note says so on stderr. On an HTTP
error the body goes to stderr and the exit code is 1 (2: usage or setup).
"""
import json
import os
import re
import stat
import sys
import urllib.error
import urllib.parse
import urllib.request

LAST_ANSWER_HEADER = "X-Portfolio-Last-Answer"
LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}


class NoRedirect(urllib.request.HTTPRedirectHandler):
    """Refuse every redirect: urllib would otherwise resend the Authorization header to
    whatever host the Location names, even over plain http."""

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


OPENER = urllib.request.build_opener(NoRedirect())

DEFAULT_ENV = "~/.config/terminal/agent.env"


DEFAULT_API = "https://api.tribulnation.com"


class Api:
    """One of the two servers: the variable that names it and its refusal hints."""

    def __init__(self, name, base_var, hints):
        self.name, self.base_var, self.hints = name, base_var, hints


class Cred:
    """One credential: the variable it is read from and the shape it must have."""

    def __init__(self, var, key_re, shape):
        self.var, self.key_re, self.shape = var, key_re, shape


APP = Api(
    "the app", "TERMINAL_BASE_URL",
    {
        401: "the key is missing, revoked, expired or mistyped (or a retired tn_pat_ token): create an API key on /integrations",
        403: "not a route this credential may read (see the API docs, /docs on the API host): an API key reads your own data with "
             "me:read, and every market data route (/api/live/, /api/market/, /api/opportunities/, /api/search, "
             "/api/asset-*) with market:read while its owner is on Ultra; nothing else",
        429: "too many requests: wait for Retry-After",
    },
)
DATA = Api(
    "the API host", "TN_API_BASE",
    {
        401: "the key is missing, revoked, expired or mistyped: run `tn terminal auth login`, or make a new key on /integrations",
        403: "the key cannot read this: /me needs the me:read scope; /v1, /v2 and /live need market:read "
             "and the Ultra plan",
        404: "no such route: check the path (filters are query parameters, never path segments)",
        410: "the route was retired (/v1/transfers/* since 2026-11-02): it answers 410 for every caller",
        429: "too many requests or the monthly quota: wait for Retry-After",
        503: "unavailable on our side (or a live snapshot `warming`): retry after Retry-After",
    },
)

KEY = Cred("TN_API_KEY", re.compile(r"^tn_key_[A-Za-z0-9_-]{43}$"), "tn_key_ and 43 characters")


def route(path):
    """The path actually read: the app's /api/live/... is the API host's /live/... (a key
    there is for the app's own pages)."""
    return "/live/" + path[len("/api/live/"):] if path.startswith("/api/live/") else path


def choices(path):
    """The server and the credentials to try, in order, for a PATH."""
    if path == "/me" or path.startswith(("/me/", "/live/")):
        return DATA, [KEY]
    if path.startswith(("/v1/", "/v2/")):
        return DATA, [KEY]
    if path.startswith("/api/"):
        # An API key reads the app routes: your own data with me:read, market data with
        # market:read (personal access tokens are retired).
        return APP, [KEY]
    return None, []


def fail(msg, code=2):
    sys.stderr.write(f"tn-api: {msg}\n")
    sys.exit(code)


def lookup(var):
    """A variable's value from the environment, else from the env file; '' when absent."""
    value = os.environ.get(var, "").strip()
    if value:
        return value
    path = os.path.expanduser(os.environ.get("TERMINAL_AGENT_ENV", DEFAULT_ENV))
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                m = re.match(rf"^\s*(?:export\s+)?{var}\s*=\s*(.*?)\s*$", line)
                if m:
                    value = m.group(1).strip().strip('"').strip("'")
    except FileNotFoundError:
        return ""
    except OSError as e:
        fail(f"cannot read {path}: {e.strerror}")
    return value


def origin(url):
    """scheme://host:port of a URL, the port spelled out, lowercased."""
    u = urllib.parse.urlsplit(url.strip())
    port = u.port or {"https": 443, "http": 80}.get(u.scheme)
    return f"{u.scheme}://{(u.hostname or '').lower()}:{port}"


def saved_login():
    """The saved login's file content when it is safe to read (a regular file of yours,
    mode 600), else None."""
    folder = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
    path = os.path.join(folder, "tn", "terminal.json")
    try:
        info = os.stat(path)
        if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
            return None
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except (OSError, ValueError):
        return None
    return data if isinstance(data, dict) else None


def api_base():
    """The API host: TN_API_BASE (TERMINAL_DATA_URL, its old name), else the host the saved
    login was issued by, else production."""
    named = os.environ.get("TN_API_BASE", "").strip() or os.environ.get("TERMINAL_DATA_URL", "").strip()
    if named:
        return named.rstrip("/")
    home = (saved_login() or {}).get("api")
    return home.strip().rstrip("/") if isinstance(home, str) and home.strip() else DEFAULT_API


def app_of(api):
    """The app beside an API host: api.X -> app.X; a host with a port (the prototype serves
    its API on a port of the app's host) -> the same host without it."""
    u = urllib.parse.urlsplit(api.strip())
    host = (u.hostname or "").lower()
    if u.port:
        return f"{u.scheme}://{host}"
    if host.startswith("api."):
        return f"{u.scheme}://app.{host[4:]}"
    return f"{u.scheme}://{host}"


def saved_key(api, base):
    """The key `tn terminal auth login` saved, and '' or why it is not used: there is none,
    the file is not safe to read (another owner, readable by others: as the CLI refuses
    it), or the key would go to another host than the one that issued it (as the CLI
    refuses: a key saved for one Terminal is never sent to another, or to whatever
    TERMINAL_BASE_URL / TN_API_BASE names). The API host must be the saved host itself;
    the app must be that host's app (`app_of`)."""
    folder = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
    path = os.path.join(folder, "tn", "terminal.json")
    try:
        info = os.stat(path)
    except OSError:
        return "", ""
    if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
        return "", f"{path} is not yours alone (chmod 600 it, or log in again)"
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except (OSError, ValueError):
        return "", f"{path} cannot be read"
    if not isinstance(data, dict):
        return "", f"{path} holds no key"
    key = data.get("key")
    if not (isinstance(key, str) and KEY.key_re.match(key)):
        return "", f"{path} holds no key"
    home = data.get("api")
    if not isinstance(home, str) or not home.strip():
        return "", f"{path} does not say which host issued its key"
    same = origin(home if api is DATA else app_of(home)) == origin(base)
    if not same:
        return "", (f"the saved key was issued by {home.strip()} and is not sent to {base}: "
                    "set TN_API_KEY, or log in there")
    return key, ""


def credentials(creds, api, base):
    """Every credential of `creds` that is set, in order, each checked for its shape: the
    first is sent, and a 403 tries the next."""
    why = ""
    found = []
    for cred in creds:
        value = lookup(cred.var)
        if not value and cred is KEY:
            value, why = saved_key(api, base)
        if not value:
            continue
        if not cred.key_re.match(value):
            fail(f"{cred.var} does not look like {cred.shape} (not shown)")
        found.append(value)
    if found:
        return found
    names = " or ".join(c.var for c in creds)
    fail(f"no credential: run `tn terminal auth login`, or set {names}" + (f" ({why})" if why else ""))


def trim(x, n, cut, at="."):
    """The first n items of every list; `cut` collects (path, items left out)."""
    if isinstance(x, list):
        if len(x) > n:
            cut.append((at, len(x) - n))
        return [trim(v, n, cut, f"{at}[]") for v in x[:n]]
    if isinstance(x, dict):
        return {k: trim(v, n, cut, f"{at.rstrip('.')}.{k}") for k, v in x.items()}
    return x


def main(argv):
    args = list(argv)
    if not args or args[0] in ("-h", "--help"):
        sys.stdout.write(__doc__)
        return 0 if args else 2
    n = None
    compact = raw = False
    rest = []
    i = 0
    while i < len(args):
        a = args[i]
        if a == "--trim":
            if i + 1 >= len(args) or not args[i + 1].isdigit():
                fail("--trim takes a number")
            n = int(args[i + 1])
            i += 2
            continue
        if a == "--compact":
            compact = True
        elif a == "--raw":
            raw = True
        else:
            rest.append(a)
        i += 1
    if not rest:
        fail("name a PATH, e.g. /api/tracker/portfolio/overview")
    path, params = route(rest[0]), rest[1:]
    api, creds = choices(path)
    if api is None:
        fail("PATH starts with /me, /v1/, /v2/, /live/ (the API host) or /api/ (the app); see the skills")
    query = []
    for p in params:
        if "=" not in p:
            fail(f"parameters are NAME=VALUE, not {p!r}")
        k, v = p.split("=", 1)
        query.append((k, v))
    base = api_base() if api is DATA else (os.environ.get(api.base_var, "").strip() or app_of(api_base())).rstrip("/")
    parsed = urllib.parse.urlsplit(base)
    if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in LOCAL_HOSTS):
        fail(f"{api.base_var} must be https:// (plain http only to localhost)")
    url = base + path + (("&" if "?" in path else "?") + urllib.parse.urlencode(query) if query else "")
    secrets = credentials(creds, api, base)
    for attempt, secret in enumerate(secrets):
        req = urllib.request.Request(url, method="GET", headers={
            "Authorization": f"Bearer {secret}",
            "Accept": "application/json",
            "User-Agent": "tn-api/1",
        })
        try:
            with OPENER.open(req, timeout=60) as r:
                body = r.read().decode("utf-8", errors="replace")
                status = r.status
                stale = r.headers.get(LAST_ANSWER_HEADER)
            break
        except urllib.error.HTTPError as e:
            # Refused for its scope or plan: the next credential that is set may read it.
            if e.code == 403 and attempt + 1 < len(secrets):
                e.close()
                continue
            err = e
        except urllib.error.URLError as e:
            fail(f"cannot reach {base}: {e.reason}", 1)
        except (TimeoutError, OSError) as e:
            fail(f"{base} did not answer: {type(e).__name__}", 1)
        if 300 <= err.code < 400:
            sys.stderr.write(
                f"tn-api: HTTP {err.code} redirect for GET {path} refused (the credential is not sent on); "
                f"check {api.base_var}\n"
            )
            return 1
        body = err.read().decode("utf-8", errors="replace")
        for s in secrets:
            body = body.replace(s, "[credential]")
        sys.stderr.write(f"tn-api: HTTP {err.code} for GET {path}\n{body[:4000]}\n")
        hint = api.hints.get(err.code)
        if hint:
            sys.stderr.write(f"tn-api: {hint}\n")
        return 1
    if stale:
        sys.stderr.write(
            f"tn-api: note: this is the stored last answer ({LAST_ANSWER_HEADER}: {stale}), "
            "the live sync failed or was slow\n"
        )
    if raw:
        sys.stdout.write(body)
        return 0
    try:
        data = json.loads(body)
    except ValueError:
        sys.stdout.write(body)
        return 0 if status < 400 else 1
    if n is not None:
        cut = []
        data = trim(data, n, cut)
        for at, more in cut[:20]:
            sys.stderr.write(f"tn-api: --trim {n}: {more} more at {at}\n")
        if len(cut) > 20:
            sys.stderr.write(f"tn-api: --trim {n}: and {len(cut) - 20} more lists cut\n")
    json.dump(data, sys.stdout, indent=None if compact else 2, ensure_ascii=False)
    sys.stdout.write("\n")
    return 0


if __name__ == "__main__":
    try:
        code = main(sys.argv[1:])
        sys.stdout.flush()
    except BrokenPipeError:
        # A reader such as `head` closed the pipe: not an error worth a traceback.
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        code = 0
    sys.exit(code)
