#!/usr/bin/env python3
"""Poll prediction scene 2 sampai selesai."""
import json, re, time, urllib.request

tools = open('TOOLS.md', encoding='utf-8').read()
m = re.search(r'Replicate API Key[\s\S]*?Token:\*\*\s*`([^`]+)`', tools)
KEY = m.group(1)

PID = "6b1zf1x1msrmw0czwm3s1rhwnc"
for i in range(40):
    req = urllib.request.Request(f"https://api.replicate.com/v1/predictions/{PID}",
        headers={"Authorization": f"Bearer {KEY}"})
    with urllib.request.urlopen(req, timeout=30) as r:
        d = json.loads(r.read())
    st = d.get("status")
    print(f"[{i}] {st}", flush=True)
    if st in ("succeeded", "failed", "canceled"):
        print(json.dumps({k: d.get(k) for k in ("output", "error", "metrics")}, indent=2, ensure_ascii=False))
        open("video_orang/pred_scene2_final.json", "w").write(json.dumps(d, indent=2))
        break
    time.sleep(15)
