"""Helios developer API quickstart: Python standard library only.

    set HELIOS_API_KEY=hk_...            (from `python -m helios keys create --tenant T --name N`)
    python examples/v1_quickstart.py [--base http://127.0.0.1:8081/v1]

1. checks the key (GET /me);
2. reads a parcel report and lists anything withheld by the licence gate;
3. submits a drawn-volume analysis as a run with an Idempotency-Key, polls the job;
4. downloads the run's memo as a PDF.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

VOLUME = {"analysis": {"kind": "volume", "storeys": 12,
                       "polygon": "-79.3662 43.6575;-79.3652 43.6575;-79.3652 43.6581;-79.3662 43.6581"}}


def call(base: str, key: str, path: str, body: dict | None = None, headers: dict | None = None, raw: bool = False):
    req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None,
                                 method="POST" if body is not None else "GET",
                                 headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json",
                                          **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=180) as r:
            data = r.read()
            return data if raw else json.loads(data)
    except urllib.error.HTTPError as e:
        problem = json.loads(e.read() or b"{}")
        sys.exit(f"{e.code} {problem.get('title', '')}: {problem.get('detail', '')}")


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--base", default=os.environ.get("HELIOS_API_BASE", "http://127.0.0.1:8081/v1"))
    p.add_argument("--parcel", default="250 Parliament St")
    p.add_argument("--out", default="helios-run.pdf")
    a = p.parse_args()
    key = os.environ.get("HELIOS_API_KEY") or sys.exit("set HELIOS_API_KEY")

    me = call(a.base, key, "/me")
    print(f"tenant {me['tenant']}, scopes {', '.join(me['scopes'])}")

    hits = call(a.base, key, f"/parcels/search?q={urllib.parse.quote(a.parcel)}&limit=1")["results"]
    if not hits:
        sys.exit("no parcel found")
    ref = hits[0]["canonical_id"]
    rep = call(a.base, key, f"/parcels/{ref}/report")
    print(f"{ref}: zone {rep['sections']['zoning']['values'].get('zone', {}).get('value')}, "
          f"gates {[(g['gate_id'], g['level']) for g in rep['gates']]}")
    if rep.get("licence"):
        print("withheld (licence):", ", ".join(rep["licence"]["withheld_sources"]))

    job = call(a.base, key, "/runs", VOLUME, headers={"Idempotency-Key": f"quickstart-{uuid.uuid4()}"})
    while job["status"] in ("queued", "running"):
        time.sleep(1)
        job = call(a.base, key, f"/jobs/{job['job_id']}")
    if job["status"] != "succeeded":
        sys.exit(f"run failed: {job.get('error')}")
    run = call(a.base, key, f"/runs/{job['run_id']}")
    print(f"run {run['run_id']} ({run['publication_status']}): {run['response']['answer'][:160]}")

    pdf = call(a.base, key, f"/runs/{job['run_id']}/memo?format=pdf", raw=True)
    with open(a.out, "wb") as f:
        f.write(pdf)
    print(f"memo saved to {a.out} ({len(pdf):,} bytes)")


if __name__ == "__main__":
    main()
