#!/usr/bin/env python3
"""Run Z-Image job files on Sarthak's Studio (copy it there) (:8484), one at a time. usage: run_local_zimage.py outdir job.json..."""
import socket
if 'Sarthaks-Mac-Studio' not in socket.gethostname(): raise SystemExit('blocked: generation runs only on Sarthak\'s Studio')
import json, sys, time, urllib.request, pathlib
out = pathlib.Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
B = "http://127.0.0.1:8484"
for f in sys.argv[2:]:
    req = json.load(open(f)); name = pathlib.Path(f).stem
    req["output"] = str(out / f"{name}.png")
    r = json.load(urllib.request.urlopen(urllib.request.Request(B + "/v1/jobs", data=json.dumps(req).encode(), headers={"Content-Type": "application/json"})))
    jid = r.get("id") or r.get("job", {}).get("id"); t0 = time.time()
    while True:
        j = json.load(urllib.request.urlopen(f"{B}/v1/jobs/{jid}")); j = j.get("job", j)
        if j["state"] in ("done", "failed", "cancelled"): break
        time.sleep(2)
    res = j.get("result") or {}
    print(name, j["state"], j.get("error"), round(time.time() - t0), "s", res.get("output"), round((res.get("peak_bytes") or 0) / 2**30, 2), "GB", flush=True)
