"""TLAY buyer quickstart: read your purchased results with an API key, download a result bundle, run a task.

Standard library only (Python 3.9+). Then verify the bundle offline with tlay_verify.py (compute.tlay.io/anchors/).

    export TLAY_API_URL=https://<deployment>/api   # the control plane API of your deployment
    export TLAY_API_KEY=tlay_ak_...                 # a buyer API key: results:read, plus jobs:run to start tasks

    python3 buyer_quickstart.py list                # your purchased tasks and their results
    python3 buyer_quickstart.py bundle <release_id> # writes tlay-result-<release_id>.json
    python3 buyer_quickstart.py run <policy_id>     # starts a purchased task (jobs:run) and waits for it

    python3 tlay_verify.py tlay-result-<release_id>.json --anchors pinned.json --strict

Keep the API key out of source code, browsers and logs; it acts as you until it expires or you revoke it.
A bundle verifies only against keys you pinned from a source other than this API (see compute.tlay.io/anchors/).
"""

from __future__ import annotations

import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from typing import Any, Optional

# A release ends in one of these; until then the job is still RESERVED or RUNNING.
FINISHED = ("COMMITTED", "SETTLEMENT_PENDING", "SETTLED", "PAYMENT_FAILED", "FAILED_SPENT")


class APIError(Exception):
    def __init__(self, status: int, code: str, message: str):
        super().__init__(f"HTTP {status} {code}: {message}")
        self.status, self.code = status, code


def call(method: str, path: str, body: Optional[dict[str, Any]] = None, idempotency_key: Optional[str] = None) -> Any:
    """One API call. Errors come back as {"code", "message", "request_id"}, some with "reason_codes" that say more
    (FORBIDDEN with API_KEY_SCOPE_MISSING, for example). Codes are stable; the message is for people."""
    headers = {"Authorization": f"Bearer {os.environ['TLAY_API_KEY']}", "Accept": "application/json"}
    data = None
    if body is not None:
        data = json.dumps(body).encode()
        headers["Content-Type"] = "application/json"
    if idempotency_key:
        # Every write carries one. Sending the same key and body again returns the first answer instead of acting twice,
        # so a write whose answer was lost can be retried safely with the same key.
        headers["Idempotency-Key"] = idempotency_key
    req = urllib.request.Request(os.environ["TLAY_API_URL"].rstrip("/") + path, data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return json.load(resp)
    except urllib.error.HTTPError as exc:
        try:
            err = json.load(exc)
        except ValueError:
            err = {}
        code = "/".join([err.get("code", "HTTP_ERROR"), *err.get("reason_codes", [])])
        raise APIError(exc.code, code, err.get("message", exc.reason)) from None


def list_results() -> None:
    out = call("GET", "/v1/buyer/results")
    for r in out["results"]:
        print(f"{r['policy_id']}  day {r['epoch_id']}  {r['release_status']:<18} release {r['release_id'] or '-'}  "
              f"ε {r['epsilon']}  labels: {', '.join(r['labels'])}")
    if not out["results"]:
        print("No purchased tasks yet: request one in the marketplace; an admin approves it.")


def save_bundle(release_id: str) -> str:
    bundle = call("GET", f"/v1/buyer/results/{release_id}/bundle")
    path = f"tlay-result-{release_id}.json"
    with open(path, "w", encoding="utf-8") as f:
        json.dump(bundle, f, indent=2)
    print(f"wrote {path} ({', '.join(bundle['labels'])})")
    return path


def run_task(policy_id: str, timeout: float = 300) -> dict[str, Any]:
    job = call("POST", "/v1/jobs", {"policy_id": policy_id}, idempotency_key=str(uuid.uuid4()))
    if job.get("note"):
        print(job["note"])  # this privacy scope already had its one release: you get that one, no new budget is spent
    deadline = time.monotonic() + timeout
    while True:
        status = call("GET", f"/v1/jobs/{job['job_id']}")
        if status["status"] in FINISHED or status.get("error_code"):
            break
        if time.monotonic() > deadline:
            raise SystemExit(f"job {job['job_id']} still {status['status']}; check again later with GET /v1/jobs/{job['job_id']}")
        time.sleep(2)
    print(f"job {status['job_id']}: {status['status']}" + (f" ({status['error_code']})" if status.get("error_code") else "")
          + f", release {status['release_id']}")
    # A failed run is final: its budget stays spent and it is never run again (FAILED_SPENT).
    return status


def main(argv: list[str]) -> int:
    for name in ("TLAY_API_URL", "TLAY_API_KEY"):
        if not os.environ.get(name):
            print(f"set {name} first (see the top of this file)", file=sys.stderr)
            return 2
    try:
        if argv[:1] == ["list"]:
            list_results()
        elif argv[:1] == ["bundle"] and len(argv) == 2:
            save_bundle(argv[1])
        elif argv[:1] == ["run"] and len(argv) == 2:
            status = run_task(argv[1])
            return 0 if status["status"] in FINISHED[:4] else 1
        else:
            print(__doc__, file=sys.stderr)
            return 2
    except APIError as exc:
        print(exc, file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
