import json, sys, time, urllib.request
B = "http://127.0.0.1:8189"
UNET = "10Eros_Max_SingularityV2_PRISM2_PikaFlex_0.85_int8HQ.safetensors"
CLIP = "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors"
VVAE = "minimax_h3_video_vae_int8_convrot.safetensors"
AVAE = "minimax_h3_audio_vae_fp32.safetensors"
IMG  = "prism2-strip-ref-01.jpg"
SIG  = "1.0, 0.972973, 0.923077, 0.8, 0.571429, 0.333333, 0.0"
CTX, CTXDIR = "h3_context/strip/clip", "h3_context/strip"

def api(path, data=None, timeout=60):
    req = urllib.request.Request(B+path, data=(json.dumps(data).encode() if data is not None else None),
        headers={"Content-Type": "application/json"}, method=("POST" if data is not None else "GET"))
    with urllib.request.urlopen(req, timeout=timeout) as f:
        return json.loads(f.read() or b"{}")

def build(i, prompt, prefix, seed, ctxlen="22", ref_key="ref_image_0", ref_size="max", img=IMG):
    wf = {
      "1": {"class_type": "UNETLoader", "inputs": {"unet_name": UNET, "weight_dtype": "default"}},
      "2": {"class_type": "CLIPLoader", "inputs": {"clip_name": CLIP, "type": "minimax", "device": "default"}},
      "3": {"class_type": "VAELoader", "inputs": {"vae_name": VVAE}},
      "4": {"class_type": "VAELoader", "inputs": {"vae_name": AVAE}},
      "5": {"class_type": "LoadImage", "inputs": {"image": img}},
      "51": {"class_type": "H3FitImage32", "inputs": {"image": ["5", 0], "max_megapixels": 0.9216,
                                                      "multiple": 32, "force_width": 0, "force_height": 0}},
      "40": {"class_type": "PrimitiveStringMultiline", "inputs": {"value": prompt}},
      "49": {"class_type": "H3PromptValidate", "inputs": {"prompt": ["40", 0], "duration": 8.0, "fix_timestamps": True}},
      "20": {"class_type": "MiniMaxH3ReferenceToVideo", "inputs": {
                "clip": ["2", 0], "vae": ["3", 0], "audio_vae": ["4", 0], "prompt": ["49", 0],
                "width": ["51", 1], "height": ["51", 2], "length": 192,
                "ref_image_size": ref_size, "ref_images." + ref_key: ["5", 0]}},
      "21": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "lcm"}},
      "22": {"class_type": "ManualSigmas", "inputs": {"sigmas": SIG}},
      "23": {"class_type": "BasicGuider", "inputs": {"model": ["1", 0], "conditioning": ["61", 0]}},
      "24": {"class_type": "RandomNoise", "inputs": {"noise_seed": seed}},
      "25": {"class_type": "SamplerCustomAdvanced", "inputs": {"noise": ["24", 0], "guider": ["23", 0], "sampler": ["21", 0],
                                                               "sigmas": ["22", 0], "latent_image": ["20", 1]}},
      "62": {"class_type": "MiniMaxH3MotionContextSaveLatent", "inputs": {"latent": ["25", 0],
                                                                         "filename_prefix": CTX, "clip_index": i}},
      "26": {"class_type": "VAEDecode", "inputs": {"samples": ["25", 0], "vae": ["3", 0]}},
      "27": {"class_type": "VAEDecodeAudio", "inputs": {"samples": ["25", 0], "vae": ["4", 0]}},
      "63": {"class_type": "MiniMaxH3MotionContextTrim", "inputs": {"images": ["26", 0], "trim_frames": ["61", 1],
                                                                    "audio": ["27", 0], "fps": 24.0, "match_tail": True}},
      "28": {"class_type": "CreateVideo", "inputs": {"images": ["63", 0], "audio": ["63", 1], "fps": 24.0}},
      "29": {"class_type": "SaveVideo", "inputs": {"video": ["28", 0], "filename_prefix": prefix, "format": "mp4", "codec": "auto"}},
      "61": {"class_type": "MiniMaxH3MotionContext", "inputs": {"conditioning": ["20", 0], "vae": ["3", 0],
                                                                "latent": ["20", 1], "context_length": ctxlen,
                                                                "audio_context_length": 24}},
    }
    if i > 1:
        wf["60"] = {"class_type": "MiniMaxH3MotionContextLoadLatent", "inputs": {"latent_path": CTXDIR, "clip_index": i - 1}}
        wf["61"]["inputs"]["context_latent"] = ["60", 0]
    return wf

def wait(pid, tag):
    t0 = time.time()
    while True:
        time.sleep(5)
        h = api("/history/" + pid, timeout=30)
        if h:
            st = h[pid].get("status", {})
            ok = st.get("status_str") == "success"
            print("[%s] %s in %.1fs" % (tag, st.get("status_str"), time.time()-t0), flush=True)
            if not ok:
                for m in st.get("messages", []):
                    if m[0] == "execution_error":
                        print("  ERR:", json.dumps(m[1], ensure_ascii=False)[:1200], flush=True)
            outs = h[pid].get("outputs", {})
            v = outs.get("29", {}).get("images") or outs.get("29", {}).get("video")
            if v: print("  OUT:", json.dumps(v, ensure_ascii=False)[:400], flush=True)
            return ok
        if time.time() - t0 > 5400:
            print("[%s] TIMEOUT" % tag, flush=True); return False

# argv: "2,3" prompt_suffix prefix_suffix seedbase ref_key ref_size
stages = [int(x) for x in sys.argv[1].split(",")]
tag_ = sys.argv[2] if len(sys.argv) > 2 else "REF"
ref_key = sys.argv[3] if len(sys.argv) > 3 else "ref_image_0"
ref_size = sys.argv[4] if len(sys.argv) > 4 else "max"
img = sys.argv[5] if len(sys.argv) > 5 else IMG
PFX = {2: "strip_s2_bodice_off", 3: "strip_s3_bra_off", 4: "strip_s4_skirt_down", 5: "strip_s5_skirt_off", 6: "strip_s6_panties_off"}
SEED = {2: 20261116, 3: 20261117, 4: 20261118, 5: 20261119, 6: 20261120}
for i in stages:
    p = "/home/zyw/h3-strip/prompts/s%d%s.txt" % (i, tag_.lower())
    prompt = open(p).read()
    wf = build(i, prompt, PFX[i] + tag_ + "_8s", SEED[i], ref_key=ref_key, ref_size=ref_size, img=img)
    q = api("/queue")
    if q["queue_running"] or q["queue_pending"]:
        print("!! queue busy", flush=True); sys.exit(1)
    r = api("/prompt", {"prompt": wf, "client_id": "strip-ref"})
    print("== stage %d queued %s (ref_key=%s)" % (i, r["prompt_id"][:8], ref_key), flush=True)
    if not wait(r["prompt_id"], "s%d" % i):
        print("!! stage %d failed" % i, flush=True); sys.exit(2)
print("DONE", flush=True)
