#!/usr/bin/env python3
"""drcli: the DiscountRunners.io command line.

Sign in once with `drcli login`, then list jobs, runs, usage and billing, get runner
recommendations, and manage monitors and warm pools. Run `drcli help` for every command.
Needs Python 3.9 or newer and nothing else.
"""

from __future__ import annotations

import argparse
import base64
import hashlib
import http.server
import json
import os
import secrets
import stat
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser

VERSION = "1.4.0"
API = os.environ.get("DR_API_URL", "https://api.discountrunners.io").rstrip("/")
CONFIG_DIR = os.environ.get("DR_CONFIG_DIR") or os.path.join(
    os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "discountrunners")
CREDENTIALS = os.path.join(CONFIG_DIR, "credentials.json")
SCOPES = "runners:read runners:write"
LOGIN_TIMEOUT = 300
USER_AGENT = f"drcli/{VERSION} (+https://discountrunners.io/docs/api)"


class Failure(Exception):
    def __init__(self, message: str, status: int = 1):
        super().__init__(message)
        self.status = status


# ---- HTTP -------------------------------------------------------------------------------------

def request(method: str, url: str, *, token: str = "", body=None, form=None, query=None):
    """Returns (status, parsed JSON or text). Never raises on an HTTP error status."""
    if query:
        pairs = [(k, str(v).lower() if isinstance(v, bool) else str(v))
                 for k, v in query.items() if v is not None and v != ""]
        if pairs:
            url += "?" + urllib.parse.urlencode(pairs)
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    data = None
    if token:
        headers["Authorization"] = f"Bearer {token}"
    if body is not None:
        data = json.dumps(body).encode()
        headers["Content-Type"] = "application/json"
    elif form is not None:
        data = urllib.parse.urlencode(form).encode()
        headers["Content-Type"] = "application/x-www-form-urlencoded"
    req = urllib.request.Request(url, data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            status, raw = r.status, r.read()
    except urllib.error.HTTPError as e:
        status, raw = e.code, e.read()
    except urllib.error.URLError as e:
        raise Failure(f"could not reach {urllib.parse.urlsplit(url).netloc}: {e.reason}") from None
    text = raw.decode("utf-8", "replace")
    try:
        return status, json.loads(text) if text else {}
    except ValueError:
        return status, text


def message_of(out) -> str:
    if isinstance(out, dict):
        err = out.get("error")
        if isinstance(err, dict):
            return err.get("message") or err.get("code") or "request failed"
        if isinstance(err, str):
            return out.get("error_description") or err
    return str(out)[:300] or "request failed"


# ---- Credentials ------------------------------------------------------------------------------

def load() -> dict:
    try:
        with open(CREDENTIALS) as f:
            data = json.load(f)
        return data if isinstance(data, dict) else {}
    except (OSError, ValueError):
        return {}


def save(data: dict) -> None:
    os.makedirs(CONFIG_DIR, mode=0o700, exist_ok=True)
    tmp = CREDENTIALS + ".tmp"
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, stat.S_IRUSR | stat.S_IWUSR)
    with os.fdopen(fd, "w") as f:
        json.dump(data, f, indent=2)
    os.replace(tmp, CREDENTIALS)


def discover() -> dict:
    status, res = request("GET", API + "/.well-known/oauth-protected-resource")
    if status != 200 or not isinstance(res, dict) or not res.get("authorization_servers"):
        raise Failure(f"{API} does not offer sign-in")
    issuer = res["authorization_servers"][0].rstrip("/")
    status, meta = request("GET", issuer + "/.well-known/oauth-authorization-server")
    if status != 200 or not isinstance(meta, dict):
        raise Failure(f"{issuer} did not describe its sign-in")
    return {"resource": res["resource"], "issuer": issuer, **meta}


def account_name(args) -> str:
    data = load()
    name = getattr(args, "account", None) or os.environ.get("DR_ACCOUNT") or data.get("default")
    if not name or name not in data.get("accounts", {}):
        known = ", ".join(sorted(data.get("accounts", {}))) or "none"
        raise Failure("not signed in; run `drcli login`" if known == "none" else
                      f"no sign-in for {name!r}; signed in to: {known}")
    return name


def refresh(name: str) -> str:
    data = load()
    acct = data["accounts"][name]
    status, out = request("POST", acct["token_endpoint"], form={
        "grant_type": "refresh_token", "refresh_token": acct["refresh_token"],
        "client_id": acct["client_id"], "resource": acct["resource"]})
    if status != 200 or not isinstance(out, dict) or "access_token" not in out:
        raise Failure(f"the sign-in for {name} has ended ({message_of(out)}); run `drcli login`")
    acct.update(access_token=out["access_token"], refresh_token=out["refresh_token"],
                expires_at=time.time() + int(out.get("expires_in", 3600)) - 60,
                scope=out.get("scope", acct.get("scope", "")))
    save(data)
    return acct["access_token"]


def token_for(args, needed: bool) -> str:
    env = os.environ.get("DR_TOKEN", "")
    if env:
        return env
    if not needed and not load().get("accounts"):
        return ""
    name = account_name(args)
    acct = load()["accounts"][name]
    if time.time() >= acct.get("expires_at", 0):
        return refresh(name)
    return acct["access_token"]


def api(args, method: str, path: str, *, query=None, body=None, signed_in: bool = True):
    token = token_for(args, signed_in)
    status, out = request(method, API + path, token=token, query=query, body=body)
    if status == 401 and token and not os.environ.get("DR_TOKEN"):
        status, out = request(method, API + path, token=refresh(account_name(args)),
                              query=query, body=body)
    if status == 401:
        raise Failure("not signed in; run `drcli login`", 4)
    if status == 403:
        raise Failure(message_of(out) + "\nRun `drcli login` and tick \"allow changes\".", 4)
    if status == 404 and message_of(out) == "no such route":
        raise Failure("this change is off for your account; an admin can turn it on under "
                      "Settings, then run `drcli login` again and allow it", 1)
    if status >= 400:
        raise Failure(message_of(out), 1)
    return out


# ---- Login ------------------------------------------------------------------------------------

class _Callback(http.server.BaseHTTPRequestHandler):
    result: dict = {}

    def do_GET(self):  # noqa: N802
        q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
        if urllib.parse.urlsplit(self.path).path != "/callback":
            self.send_response(404)
            self.end_headers()
            return
        type(self).result = {k: v[0] for k, v in q.items()}
        ok = "code" in q
        page = ("<h1>Signed in</h1><p>You can close this tab and return to the terminal.</p>"
                if ok else "<h1>Sign-in was not completed</h1><p>Return to the terminal.</p>")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()
        self.wfile.write(f"<!doctype html><title>drcli</title>{page}".encode())

    def log_message(self, *a):
        pass


def cmd_login(args) -> None:
    meta = discover()
    server = http.server.HTTPServer(("127.0.0.1", 0), _Callback)
    redirect = f"http://127.0.0.1:{server.server_address[1]}/callback"
    data = load()
    client_id = data.get("clients", {}).get(meta["issuer"])
    if not client_id:
        status, reg = request("POST", meta["registration_endpoint"], body={
            "client_name": "DiscountRunners CLI", "redirect_uris": [redirect],
            "token_endpoint_auth_method": "none"})
        if status not in (200, 201) or not isinstance(reg, dict):
            raise Failure(f"could not register the CLI: {message_of(reg)}")
        client_id = reg["client_id"]
        data.setdefault("clients", {})[meta["issuer"]] = client_id
        save(data)
    verifier = secrets.token_urlsafe(64)
    challenge = base64.urlsafe_b64encode(
        hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
    state = secrets.token_urlsafe(16)
    url = meta["authorization_endpoint"] + "?" + urllib.parse.urlencode({
        "response_type": "code", "client_id": client_id, "redirect_uri": redirect,
        "code_challenge": challenge, "code_challenge_method": "S256", "state": state,
        "scope": SCOPES, "resource": meta["resource"]})
    _Callback.result = {}
    threading.Thread(target=server.serve_forever, daemon=True).start()
    print("Opening your browser to sign in. If it does not open, visit:\n  " + url,
          file=sys.stderr)
    if not args.no_browser:
        webbrowser.open(url)
    deadline = time.time() + LOGIN_TIMEOUT
    while not _Callback.result and time.time() < deadline:
        time.sleep(0.2)
    server.shutdown()
    got = _Callback.result
    if not got:
        raise Failure("sign-in timed out")
    if got.get("state") != state:
        raise Failure("sign-in answer did not match this request; try again")
    if "code" not in got:
        raise Failure(f"sign-in was not completed: {got.get('error', 'denied')}")
    if got.get("iss") and got["iss"].rstrip("/") != meta["issuer"]:
        raise Failure("sign-in answer came from an unexpected server")
    status, tok = request("POST", meta["token_endpoint"], form={
        "grant_type": "authorization_code", "code": got["code"], "redirect_uri": redirect,
        "client_id": client_id, "code_verifier": verifier, "resource": meta["resource"]})
    if status != 200 or not isinstance(tok, dict) or "access_token" not in tok:
        raise Failure(f"sign-in failed: {message_of(tok)}")
    status, me = request("GET", API + "/v1/account", token=tok["access_token"])
    if status != 200 or not isinstance(me, dict):
        raise Failure(f"signed in, but the account could not be read: {message_of(me)}")
    name = me["account"]
    data = load()
    data.setdefault("accounts", {})[name] = {
        "client_id": client_id, "access_token": tok["access_token"],
        "refresh_token": tok["refresh_token"], "scope": tok.get("scope", ""),
        "expires_at": time.time() + int(tok.get("expires_in", 3600)) - 60,
        "token_endpoint": meta["token_endpoint"],
        "revocation_endpoint": meta.get("revocation_endpoint", ""),
        "resource": meta["resource"]}
    data["default"] = name
    save(data)
    can = "read and change" if "runners:write" in tok.get("scope", "") else "read"
    print(f"Signed in to {name}; this sign-in may {can} the account.", file=sys.stderr)


def cmd_logout(args) -> None:
    data = load()
    name = account_name(args)
    acct = data["accounts"].pop(name)
    if acct.get("revocation_endpoint"):
        request("POST", acct["revocation_endpoint"], form={"token": acct["refresh_token"]})
    if data.get("default") == name:
        data["default"] = next(iter(sorted(data["accounts"])), None)
    save(data)
    print(f"Signed out of {name}.", file=sys.stderr)


def cmd_accounts(args) -> dict:
    data = load()
    return {"default": data.get("default"), "accounts": [
        {"account": n, "scope": a.get("scope", ""), "default": n == data.get("default")}
        for n, a in sorted(data.get("accounts", {}).items())]}


def cmd_switch(args) -> None:
    data = load()
    if args.name not in data.get("accounts", {}):
        raise Failure(f"no sign-in for {args.name!r}; run `drcli login`")
    data["default"] = args.name
    save(data)
    print(f"Now using {args.name}.", file=sys.stderr)


# ---- Output -----------------------------------------------------------------------------------

def _cell(v) -> str:
    if v is None:
        return ""
    if isinstance(v, bool):
        return "yes" if v else "no"
    if isinstance(v, float):
        return f"{v:.1f}" if abs(v) >= 10 else f"{v:.2f}"
    if isinstance(v, (dict, list)):
        return json.dumps(v, separators=(",", ":"))[:60]
    s = str(v)
    if len(s) >= 19 and s[4] == "-" and s[10] == "T":
        return s[:16].replace("T", " ")
    return s


def table(rows: list, columns: list) -> str:
    if not rows:
        return "(none)"
    cells = [[_cell(r.get(c)) for c in columns] for r in rows]
    width = [max(len(c), *(len(row[i]) for row in cells)) for i, c in enumerate(columns)]
    width = [min(w, 48) for w in width]
    out = ["  ".join(c.upper().ljust(width[i]) for i, c in enumerate(columns)).rstrip()]
    for row in cells:
        out.append("  ".join((v if len(v) <= width[i] else v[:width[i] - 1] + "…")
                             .ljust(width[i]) for i, v in enumerate(row)).rstrip())
    return "\n".join(out)


def pairs(d: dict, skip=()) -> str:
    keys = [k for k, v in d.items() if k not in skip and not isinstance(v, (dict, list))]
    w = max((len(k) for k in keys), default=0)
    return "\n".join(f"{k.replace('_', ' ').ljust(w)}  {_cell(d[k])}" for k in keys)


VIEWS = {
    "jobs": ("jobs", ["job_id", "repository", "workflow", "job", "runner_class", "state",
                      "queue_seconds", "run_seconds", "charged_usd", "started_at"]),
    "runs": ("runs", ["run_id", "repository", "workflow", "jobs", "state", "branch",
                      "run_seconds", "charged_usd", "started_at"]),
    "repos": ("repositories", ["repository", "private", "connected", "jobs_here",
                               "minutes_here", "spend_usd"]),
    "classes": ("classes", ["label", "vcpus", "physical_cores", "memory_gib", "arch",
                            "image", "price_per_minute_usd",
                            "github_hosted_price_per_minute_usd"]),
    "ledger": ("entries", ["id", "at", "kind", "amount_usd", "balance_after_usd", "job_id",
                           "memo"]),
    "monitors": ("monitors", ["monitor_id", "name", "enabled", "trigger", "repository",
                              "workflow", "job"]),
    "pools": ("warm_pools", ["pool_id", "runner_class", "repository", "enabled", "boxes_ready",
                             "spent_this_month_usd", "monthly_estimate_usd"]),
    "recommend": ("recommendations", ["workflow", "job", "runner_class", "kind", "to", "why"]),
    "profile": ("jobs", ["workflow", "job", "runner_class", "runs", "failed",
                         "run_seconds_p50", "run_seconds_p95", "cpu_p95_median",
                         "smaller_class", "spend_usd"]),
    "history": ("jobs", ["job_id", "workflow", "job", "runner_class", "status", "conclusion",
                         "wait_seconds", "run_seconds", "cost_usd"]),
    "runners": ("jobs", ["workflow", "job", "provider", "labels", "jobs_seen",
                         "last_seen_at"]),
    "storage": ("items", ["id", "repository", "key", "name", "label", "region", "bytes",
                          "last_used"]),
}


def show(args, out, view: str | None = None) -> None:
    as_json = args.json or (not sys.stdout.isatty() and not args.table)
    if as_json or not isinstance(out, dict):
        print(json.dumps(out, indent=2))
        return
    if view == "run":
        print(pairs(out, skip=("jobs",)) + "\n")
        print(table(out.get("jobs", []), VIEWS["jobs"][1]))
    elif view == "job":
        print(pairs(out) + "\n")
        print(table(out.get("timeline", []), ["step", "detail", "at", "state"]))
    elif view == "usage":
        print(pairs(out) + "\n")
        print(table(out.get("by_repository", []),
                    ["repository", "jobs", "billed_minutes", "charged_usd"]))
    elif view in VIEWS:
        key, cols = VIEWS[view]
        rows = out.get(key, [])
        print(table(rows if isinstance(rows, list) else [], cols))
        for more in ("next_cursor", "next_before"):
            if out.get(more):
                flag = "--cursor" if more == "next_cursor" else "--before"
                print(f"\nMore: add {flag} {out[more]}", file=sys.stderr)
    else:
        print(pairs(out) or json.dumps(out, indent=2))


# ---- Commands ---------------------------------------------------------------------------------

def _repo_path(repo: str, tail: str) -> str:
    owner, sep, name = repo.partition("/")
    if not sep or not owner or not name or "/" in name:
        raise Failure("give the repository as owner/name")
    return f"/v1/repositories/{urllib.parse.quote(owner)}/{urllib.parse.quote(name)}/{tail}"


def _list_query(a) -> dict:
    return {"status": a.status, "search": a.search, "days": a.days, "limit": a.limit,
            "cursor": a.cursor}


def run(args) -> None:
    c = args.command
    if c == "login":
        return cmd_login(args)
    if c == "logout":
        return cmd_logout(args)
    if c == "switch":
        return cmd_switch(args)
    if c == "accounts":
        return show(args, cmd_accounts(args), None)
    if c == "version":
        return print(f"drcli {VERSION}")
    if c == "whoami" or c == "account":
        return show(args, api(args, "GET", "/v1/account"))
    if c == "classes":
        return show(args, api(args, "GET", "/v1/classes", signed_in=False, query={
            "arch": args.arch, "image": args.image, "min_vcpus": args.min_vcpus}), "classes")
    if c == "quote":
        return show(args, api(args, "GET", "/v1/quote", signed_in=False, query={
            "runner_class": args.runner_class, "seconds": args.minutes * 60,
            "runs": args.runs, "compare_to": args.compare_to}))
    if c == "jobs":
        if args.job_id:
            path = f"/v1/jobs/{args.job_id}" + ("/explanation" if args.explain else "")
            return show(args, api(args, "GET", path), None if args.explain else "job")
        return show(args, api(args, "GET", "/v1/jobs", query=_list_query(args)), "jobs")
    if c == "runs":
        if args.run_id:
            return show(args, api(args, "GET", f"/v1/runs/{args.run_id}",
                                  query={"attempt": args.attempt}), "run")
        return show(args, api(args, "GET", "/v1/runs", query=_list_query(args)), "runs")
    if c == "usage":
        return show(args, api(args, "GET", "/v1/usage", query={"month": args.month}), "usage")
    if c == "ledger":
        return show(args, api(args, "GET", "/v1/ledger", query={
            "before": args.before, "limit": args.limit}), "ledger")
    if c == "repos":
        if args.connect or args.disconnect:
            if not args.repo:
                raise Failure("give the repository as owner/name")
            return show(args, api(args, "PATCH", _repo_path(args.repo, "connection"),
                                  body={"connected": bool(args.connect)}))
        if args.repo:
            tail = {"history": "jobs", "profile": "profile", "recommend": "recommendations",
                    "runners": "runners"}[args.view]
            return show(args, api(args, "GET", _repo_path(args.repo, tail),
                                  query={"days": args.days}), args.view)
        return show(args, api(args, "GET", "/v1/repositories", query={"days": args.days}),
                    "repos")
    if c == "recommend":
        return show(args, api(args, "GET", _repo_path(args.repo, "recommendations"),
                              query={"days": args.days}), "recommend")
    if c == "labels":
        if args.new is not None:
            return show(args, api(args, "POST", "/v1/labels/check", signed_in=False,
                                  body={"old": args.runs_on, "new": args.new}))
        return show(args, api(args, "POST", "/v1/labels/map", signed_in=False,
                              body={"runs_on": args.runs_on}))
    if c == "monitors":
        if args.action == "delete":
            return show(args, api(args, "DELETE", f"/v1/monitors/{args.id}"))
        return show(args, api(args, "GET", "/v1/monitors"), "monitors")
    if c == "pools":
        if args.action == "delete":
            return show(args, api(args, "DELETE", f"/v1/warm-pools/{args.id}"))
        if args.action in ("on", "off"):
            return show(args, api(args, "PATCH", f"/v1/warm-pools/{args.id}",
                                  body={"enabled": args.action == "on"}))
        return show(args, api(args, "GET", "/v1/warm-pools"), "pools")
    if c == "telemetry":
        path = "/v1/telemetry-export"
        if args.action == "test":
            return show(args, api(args, "POST", path + "/test"))
        if args.action == "delete":
            return show(args, api(args, "DELETE", path))
        if args.action in ("on", "off"):
            return show(args, api(args, "PATCH", path, body={"enabled": args.action == "on"}))
        if args.action == "set":
            body = {"endpoint": args.endpoint, "service_name": args.service_name,
                    "traces": args.traces, "metrics": args.metrics,
                    "scrub_secrets": args.scrub, "logs": args.logs}
            if args.headers_stdin:
                headers = {}
                for line in sys.stdin.read().splitlines():
                    if line.strip():
                        name, sep, value = line.partition(":")
                        if not sep:
                            raise Failure("write each header as Name: value")
                        headers[name.strip()] = value.strip()
                body["headers"] = headers
            return show(args, api(args, "PATCH", path,
                                  body={k: v for k, v in body.items() if v is not None}))
        out = api(args, "GET", path)
        return show(args, out.get("export") or {"export": "none"})
    if c == "settings":
        if args.action == "show":
            return show(args, api(args, "GET", "/v1/account/settings"))
        everyday = {"job_log_costs": args.job_log_costs, "automatic_reruns": args.reruns,
                    "npm_mirror": args.npm_mirror, "pypi_mirror": args.pypi_mirror,
                    "credit_email_to": [] if args.no_credit_email else args.credit_email}
        controls = {"monthly_cap_usd": args.cap, "remove_cap": args.no_cap or None,
                    "concurrency_limit": args.concurrency,
                    "size_trial_cap_usd": args.trial_cap,
                    "remove_size_trial_cap": args.no_trial_cap or None,
                    "auto_upgrade": args.auto_upgrade}
        everyday = {k: v for k, v in everyday.items() if v is not None}
        controls = {k: v for k, v in controls.items() if v is not None}
        if not everyday and not controls:
            raise Failure("give at least one setting to change; see drcli settings --help")
        out = {}
        if everyday:
            out = api(args, "PATCH", "/v1/account/settings", body=everyday)
        if controls:
            out = api(args, "PATCH", "/v1/account/controls", body=controls)
        return show(args, out)
    if c == "storage":
        if args.action == "delete":
            if bool(args.id) == args.all:
                raise Failure("give --id for each entry to delete, or --all, not both")
            body = {"kind": args.kind, "repository": args.repo, "key": args.key}
            body |= {"all": True} if args.all else {"ids": args.id}
            return show(args, api(args, "POST", "/v1/storage/delete",
                                  body={k: v for k, v in body.items() if v not in (None, "")}))
        return show(args, api(args, "GET", "/v1/storage", query={
            "kind": args.kind, "repository": args.repo, "key": args.key}), "storage")
    if c == "ssh":
        if args.action == "set":
            body = {"enabled": args.on, "linger_minutes": args.linger, "who": args.who}
            return show(args, api(args, "PATCH", "/v1/account/ssh",
                                  body={k: v for k, v in body.items() if v is not None}))
        if args.job_id is None:
            raise Failure("give the job id: drcli ssh ask <job_id>")
        return show(args, api(args, "POST", f"/v1/jobs/{args.job_id}/ssh"))
    if c == "api":
        body = None
        if args.data is not None:
            raw = sys.stdin.read() if args.data == "-" else args.data
            try:
                body = json.loads(raw)
            except ValueError:
                raise Failure("--data must be JSON") from None
        path = args.path if args.path.startswith("/") else "/" + args.path
        query = dict(f.split("=", 1) for f in args.field) if args.field else None
        return show(args, api(args, args.method.upper(), path, query=query, body=body,
                              signed_in=bool(load().get("accounts")) or bool(
                                  os.environ.get("DR_TOKEN"))))
    raise Failure(f"unknown command {c!r}; run `drcli help`")


def parser() -> argparse.ArgumentParser:
    def flags(suppress: bool) -> argparse.ArgumentParser:
        # A subcommand's copy must not reset a flag given before the subcommand.
        kw = {"default": argparse.SUPPRESS} if suppress else {}
        f = argparse.ArgumentParser(add_help=False)
        f.add_argument("--json", action="store_true", help="print JSON (the default when piped)",
                       **kw)
        f.add_argument("--table", action="store_true", help="print a table even when piped",
                       **kw)
        f.add_argument("--account", help="account to use when signed in to several", **kw)
        return f

    common = flags(True)
    p = argparse.ArgumentParser(prog="drcli", description="DiscountRunners.io from the terminal.",
                                parents=[flags(False)])
    sub = p.add_subparsers(dest="command", metavar="<command>")

    def add(name, help_, **kw):
        return sub.add_parser(name, help=help_, description=help_, parents=[common], **kw)

    login = add("login", "Sign in with GitHub in your browser")
    login.add_argument("--no-browser", action="store_true", help="only print the sign-in URL")
    add("logout", "Sign out and revoke this computer's sign-in")
    add("accounts", "List the accounts you are signed in to")
    sw = add("switch", "Use another signed-in account by default")
    sw.add_argument("name")
    add("whoami", "Show the account, balance, caps and concurrency limit")
    add("version", "Print the CLI version")

    cl = add("classes", "List runner classes and prices")
    cl.add_argument("--arch", choices=("x64", "arm64"))
    cl.add_argument("--image", choices=("slim", "full", "full26"))
    cl.add_argument("--min-vcpus", type=int)
    q = add("quote", "Price a job on one of our classes against GitHub or a competitor")
    q.add_argument("runner_class")
    q.add_argument("minutes", type=float)
    q.add_argument("--runs", type=int, default=1, help="runs to price, e.g. per month")
    q.add_argument("--compare-to", default=None, help="competitor slug; github by default")

    def listing(cmd):
        cmd.add_argument("--status", default="all", choices=(
            "all", "waiting", "running", "succeeded", "failed", "cancelled", "preempted"))
        cmd.add_argument("--search", default="", help="words, a job or run id, or a commit")
        cmd.add_argument("--days", type=int, default=7)
        cmd.add_argument("--limit", type=int, default=50)
        cmd.add_argument("--cursor", default="", help="continue a previous page")

    j = add("jobs", "List jobs, or show one with its timeline")
    j.add_argument("job_id", nargs="?", type=int)
    j.add_argument("--explain", action="store_true", help="why the job is in its state")
    listing(j)
    r = add("runs", "List workflow runs, or show one run's jobs")
    r.add_argument("run_id", nargs="?", type=int)
    r.add_argument("--attempt", type=int)
    listing(r)
    u = add("usage", "Show a month's charges by repository, day and class")
    u.add_argument("--month", default="", help="YYYY-MM; this month by default")
    led = add("ledger", "Show the balance and ledger entries")
    led.add_argument("--before", type=int)
    led.add_argument("--limit", type=int, default=50)
    rp = add("repos", "List repositories, or show one repository's jobs or profile")
    rp.add_argument("repo", nargs="?", help="owner/name")
    rp.add_argument("--view", default="history",
                    choices=("history", "profile", "recommend", "runners"))
    rp.add_argument("--days", type=int, default=30)
    on_off = rp.add_mutually_exclusive_group()
    on_off.add_argument("--disconnect", action="store_true",
                        help="stop new jobs from this repository running here")
    on_off.add_argument("--connect", action="store_true",
                        help="let a disconnected repository's jobs run here again")
    rec = add("recommend", "Recommend runner changes for a repository")
    rec.add_argument("repo", help="owner/name")
    rec.add_argument("--days", type=int, default=30)
    lb = add("labels", "Map a runs-on value to our class, or check a rewrite")
    lb.add_argument("runs_on", help="the runs-on value as written")
    lb.add_argument("new", nargs="?", help="a proposed new value to check")
    mo = add("monitors", "List or delete job monitors")
    mo.add_argument("action", nargs="?", choices=("list", "delete"), default="list")
    mo.add_argument("id", nargs="?", type=int)
    po = add("pools", "List warm pools, turn one on or off, or delete one")
    po.add_argument("action", nargs="?", choices=("list", "on", "off", "delete"),
                    default="list")
    po.add_argument("id", nargs="?", type=int)
    te = add("telemetry", "Show, set, test, pause or delete the OpenTelemetry export")
    te.add_argument("action", nargs="?", choices=("show", "set", "test", "on", "off", "delete"),
                    default="show")
    te.add_argument("--endpoint", help="OTLP/HTTP base address, e.g. https://api.honeycomb.io")
    te.add_argument("--headers-stdin", action="store_true",
                    help="read every header as Name: value lines from stdin; replaces them")
    te.add_argument("--service-name")
    te.add_argument("--traces", action=argparse.BooleanOptionalAction, default=None)
    te.add_argument("--metrics", action=argparse.BooleanOptionalAction, default=None)
    te.add_argument("--logs", action=argparse.BooleanOptionalAction, default=None,
                    help="send each job's log lines (off unless turned on)")
    te.add_argument("--scrub", action=argparse.BooleanOptionalAction, default=None,
                    help="mask secret-looking text before sending")
    st = add("settings", "Show or change the account's settings and controls")
    st.add_argument("action", nargs="?", choices=("show", "set"), default="show")
    on_off = argparse.BooleanOptionalAction
    st.add_argument("--job-log-costs", action=on_off, default=None,
                    help="end each job's log with its cost and saving")
    st.add_argument("--reruns", action=on_off, default=None,
                    help="re-run failed jobs once, automatically, when the failure wasn't "
                         "theirs")
    st.add_argument("--npm-mirror", action=on_off, default=None)
    st.add_argument("--pypi-mirror", action=on_off, default=None)
    st.add_argument("--credit-email", action="append", default=None, metavar="ADDRESS",
                    help="who is emailed about runs held for credit; repeat for several")
    st.add_argument("--no-credit-email", action="store_true", help="stop credit emails")
    st.add_argument("--cap", help="monthly spending cap in dollars (needs controls turned on)")
    st.add_argument("--no-cap", action="store_true", help="remove the monthly spending cap")
    st.add_argument("--concurrency", type=int, help="most runners at once")
    st.add_argument("--trial-cap", help="most a size trial may spend, in dollars")
    st.add_argument("--no-trial-cap", action="store_true", help="remove the size-trial cap")
    st.add_argument("--auto-upgrade", action=on_off, default=None,
                    help="let jobs run on a bigger machine at no extra charge")
    sg = add("storage", "List or delete caches, sticky disks and repository images")
    sg.add_argument("action", nargs="?", choices=("list", "delete"), default="list")
    sg.add_argument("--kind", choices=("cache", "sticky", "image"), default="cache")
    sg.add_argument("--repo", help="owner/name; one repository only")
    sg.add_argument("--key", default="", help="only keys containing this text")
    sg.add_argument("--id", type=int, action="append", help="an entry to delete; repeat")
    sg.add_argument("--all", action="store_true", help="delete every entry that matches")
    sh = add("ssh", "Ask to SSH into a job, or change SSH debugging")
    sh.add_argument("action", choices=("ask", "set"))
    sh.add_argument("job_id", nargs="?", type=int)
    sh.add_argument("--on", action=on_off, default=None, help="allow SSH into jobs")
    sh.add_argument("--linger", type=int, choices=(0, 5, 10, 15, 30),
                    help="minutes a finished job's runner stays up")
    sh.add_argument("--who", choices=("admins", "actors"))
    ap = add("api", "Call any API route, e.g. drcli api GET /v1/jobs -f status=failed")
    ap.add_argument("method", choices=("GET", "POST", "PATCH", "DELETE", "get", "post",
                                       "patch", "delete"))
    ap.add_argument("path")
    ap.add_argument("-f", "--field", action="append", default=[], help="key=value query field")
    ap.add_argument("-d", "--data", help="JSON body, or - to read it from stdin")
    add("help", "Show this help")
    return p


def main(argv=None) -> int:
    p = parser()
    args = p.parse_args(argv)
    if args.command in (None, "help"):
        p.print_help()
        return 0
    needs_id = {"monitors": ("delete",), "pools": ("on", "off", "delete")}
    if args.command in needs_id and args.action in needs_id[args.command] and args.id is None:
        p.error(f"{args.command} {args.action} needs an id")
    try:
        run(args)
    except Failure as e:
        print(f"drcli: {e}", file=sys.stderr)
        return e.status
    except KeyboardInterrupt:
        return 130
    return 0


if __name__ == "__main__":
    sys.exit(main())
