"""Massalaskuri Partner API - end-to-end in Python (stdlib only).
Usage:  API_KEY=mlk_xxx python3 example.py [path/to/plan.pdf]
"""
import os, sys, json, time, urllib.request

BASE = os.environ.get("BASE", "https://api.massalaskuri.com")
KEY = os.environ["API_KEY"]  # set API_KEY=mlk_...
pdf_path = sys.argv[1] if len(sys.argv) > 1 else "sample-plan.pdf"


def req(method, url, data=None, headers=None, raw=False):
    r = urllib.request.Request(url, data=data, method=method, headers=headers or {})
    with urllib.request.urlopen(r) as resp:
        body = resp.read()
        return body if raw else json.loads(body)


def main():
    with open(pdf_path, "rb") as f:
        data = f.read()

    # 1) init
    init = req("POST", f"{BASE}/v1/jobs/init",
               data=json.dumps({"file_name": os.path.basename(pdf_path), "mime_type": "application/pdf",
                                "size": len(data), "external_ref": "python-example"}).encode(),
               headers={"X-API-Key": KEY, "Content-Type": "application/json"})
    job_id = init["job_id"]
    print("job", job_id)

    # 2) upload (token is in the URL; no API key here)
    req("PUT", init["upload"]["url"], data=data, headers={"Content-Type": "application/pdf"}, raw=True)

    # 3) start
    req("POST", f"{BASE}/v1/jobs/{job_id}/start", headers={"X-API-Key": KEY})

    # 4) poll
    while True:
        job = req("GET", f"{BASE}/v1/jobs/{job_id}", headers={"X-API-Key": KEY})
        print("status", job["status"])
        if job["status"] == "done":
            break
        if job["status"] == "failed":
            raise SystemExit(job.get("error"))
        time.sleep(4)

    # 5) results
    print("total detections:", job["summary"]["total_detections"])
    for s in job["summary"]["by_symbol"][:10]:
        print(f"  {s['count']:>4}  {s['display_name']}  ({s.get('talo2010_code') or '-'})")


if __name__ == "__main__":
    main()
