import json, sys, time, requests

import os
WF = os.environ.get("WF", "/home/ly/DSH/projects/h3-video/contest-jianxin/交付/浪客剑心-打斗素材包-20261120/workflows/01_原始比赛版.json")
PORTS = [8192, 8193]
w, h, length = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])
prefix = sys.argv[4]

wf = json.load(open(WF))
wf["20"]["inputs"].update({"width": w, "height": h, "length": length})
wf["30"]["inputs"]["noise_seed"] = int(os.environ.get("SEED", "20261118"))
wf["43"]["inputs"]["filename_prefix"] = prefix
print(f"提交 {w}x{h} / {length} 帧 → {PORTS}", flush=True)

ids = {}
for p in PORTS:
    r = requests.post(f"http://127.0.0.1:{p}/prompt", json={"prompt": wf, "client_id": "nv-tp-test"}, timeout=30)
    j = r.json()
    if r.status_code != 200:
        print(f"[{p}] FAIL {r.status_code}: {json.dumps(j, ensure_ascii=False)[:800]}", flush=True)
        sys.exit(1)
    ids[p] = j["prompt_id"]
    print(f"[{p}] queued {j['prompt_id']}", flush=True)

t0 = time.time()
done = {}
while time.time() - t0 < 1800:
    for p in PORTS:
        if p in done: continue
        try:
            h_ = requests.get(f"http://127.0.0.1:{p}/history/{ids[p]}", timeout=10).json()
            if ids[p] in h_:
                st = h_[ids[p]].get("status", {})
                if st.get("completed") or st.get("status_str") == "success":
                    done[p] = time.time() - t0
                    print(f"[{p}] DONE {done[p]:.1f}s", flush=True)
                elif st.get("status_str") == "error":
                    print(f"[{p}] ERROR {json.dumps(st, ensure_ascii=False)[:800]}", flush=True)
                    done[p] = -1
        except Exception as e:
            pass
    if len(done) == 2:
        break
    if int(time.time()-t0) % 30 < 2:
        print(f"  ... {int(time.time()-t0)}s", flush=True)
    time.sleep(2)
print("RESULT", done, flush=True)
