#!/usr/bin/env python3
import json, sys, time, urllib.request, urllib.error, urllib.parse, os

API = "http://127.0.0.1:8189"
W, H, LEN, FPS, STEPS = 544, 960, 141, 24, 20
SEED = 20261019

def req(path, data=None):
    url = API + path
    if data is not None:
        data = json.dumps(data).encode()
        r = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
    else:
        r = urllib.request.Request(url)
    with urllib.request.urlopen(r, timeout=60) as f:
        return json.loads(f.read().decode())

def base_nodes(prompt_text, with_video_ref=True):
    n = {}
    n["1"] = {"class_type": "UNETLoader", "inputs": {
        "unet_name": "MiniMaxH3/minimax_h3_ref2va_pruned_int8_convrot.safetensors",
        "weight_dtype": "default"}}
    n["2"] = {"class_type": "CLIPLoader", "inputs": {
        "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
        "type": "minimax", "device": "default"}}
    n["3"] = {"class_type": "VAELoader", "inputs": {
        "vae_name": "MiniMaxH3/minimax_h3_video_vae_int8_convrot.safetensors"}}
    n["4"] = {"class_type": "VAELoader", "inputs": {
        "vae_name": "MiniMaxH3/minimax_h3_audio_vae_fp32.safetensors"}}
    n["5"] = {"class_type": "LoadVideo", "inputs": {"file": "depth_da3_h3.mp4"}}
    n["6"] = {"class_type": "GetVideoComponents", "inputs": {"video": ["5", 0]}}
    n["10"] = {"class_type": "LoadImage", "inputs": {"image": "face_front.jpg"}}
    n["11"] = {"class_type": "LoadImage", "inputs": {"image": "home_front.jpg"}}
    n["12"] = {"class_type": "LoadImage", "inputs": {"image": "heels_front.jpg"}}
    n["13"] = {"class_type": "LoadImage", "inputs": {"image": "grip_heel.jpg"}}
    n["14"] = {"class_type": "LoadImage", "inputs": {"image": "hand_ref.png"}}
    n["60"] = {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["1", 0], "lora_name": "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors", "strength_model": 1.0}}
    ref = {
        "clip": ["2", 0], "vae": ["3", 0], "audio_vae": ["4", 0],
        "prompt": prompt_text, "width": W, "height": H, "length": LEN,
        "ref_image_size": "match",
        "ref_images.ref_image_0": ["10", 0],
        "ref_images.ref_image_1": ["11", 0],
        "ref_images.ref_image_2": ["12", 0],
        "ref_images.ref_image_3": ["13", 0],
        "ref_images.ref_image_4": ["14", 0],
    }
    if with_video_ref:
        ref["ref_videos.ref_video_0"] = ["6", 0]
    n["20"] = {"class_type": "MiniMaxH3ReferenceToVideo", "inputs": ref}
    return n

def sampler(n, model_ref, cond_ref, latent_ref, tag):
    n["30"] = {"class_type": "RandomNoise", "inputs": {"noise_seed": SEED}}
    n["31"] = {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "res_multistep"}}
    n["32"] = {"class_type": "BasicScheduler", "inputs": {
        "model": model_ref, "scheduler": "simple", "steps": STEPS, "denoise": 1.0}}
    n["33"] = {"class_type": "BasicGuider", "inputs": {
        "model": model_ref, "conditioning": cond_ref}}
    n["34"] = {"class_type": "SamplerCustomAdvanced", "inputs": {
        "noise": ["30", 0], "guider": ["33", 0], "sampler": ["31", 0],
        "sigmas": ["32", 0], "latent_image": latent_ref}}
    n["40"] = {"class_type": "VAEDecode", "inputs": {"samples": ["34", 0], "vae": ["3", 0]}}
    n["41"] = {"class_type": "VAEDecodeAudio", "inputs": {"samples": ["34", 0], "vae": ["4", 0]}}
    n["42"] = {"class_type": "CreateVideo", "inputs": {
        "images": ["40", 0], "audio": ["41", 0], "fps": float(FPS)}}
    n["43"] = {"class_type": "SaveVideo", "inputs": {
        "video": ["42", 0], "filename_prefix": "h3_" + tag + "/wardrobe",
        "format": "auto", "codec": "auto"}}
    return n

def graph_ref(prompt_text):
    n = base_nodes(prompt_text, with_video_ref=True)
    return sampler(n, ["1", 0], ["20", 0], ["20", 1], "ref2va_v9")

def graph_fun(prompt_text):
    n = base_nodes(prompt_text, with_video_ref=False)
    n["50"] = {"class_type": "ModelPatchLoader", "inputs": {
        "name": "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"}}
    n["51"] = {"class_type": "MiniMaxH3FunControlNetApply", "inputs": {
        "model": ["1", 0], "model_patch": ["50", 0], "vae": ["3", 0],
        "strength": 1.0, "start_percent": 0.0, "end_percent": 1.0,
        "control_video": ["6", 0]}}
    return sampler(n, ["51", 0], ["20", 0], ["20", 1], "funcontrol_v9")

def submit(prompt, label):
    try:
        r = req("/prompt", {"prompt": prompt, "client_id": "dsh-h3"})
    except urllib.error.HTTPError as e:
        print("HTTP", e.code, e.read().decode()[:4000]); raise
    print("SUBMIT", label, json.dumps(r)[:600], flush=True)
    if r.get("node_errors"):
        print("NODE ERRORS", json.dumps(r["node_errors"], indent=2)[:6000]); raise SystemExit(2)
    return r["prompt_id"]

def wait(pid):
    t0 = time.time()
    while True:
        h = req("/history/" + pid)
        if pid in h:
            item = h[pid]
            print("DONE", pid, "status", item.get("status", {}), flush=True)
            return item
        q = req("/queue")
        run = len(q.get("queue_running", [])); pend = len(q.get("queue_pending", []))
        print("wait", int(time.time()-t0), "s run", run, "pend", pend, flush=True)
        time.sleep(10)

def download(item, out):
    outs = item.get("outputs", {})
    files = []
    for node, o in outs.items():
        for k, v in o.items():
            if isinstance(v, list):
                for it in v:
                    if isinstance(it, dict) and it.get("filename"):
                        files.append(it)
    print("FILES", json.dumps(files)[:800], flush=True)
    for it in files:
        if it.get("type", "output") != "output":
            continue
        q = urllib.parse.urlencode({"filename": it["filename"], "subfolder": it.get("subfolder",""), "type": it.get("type","output")})
        data = urllib.request.urlopen(API + "/view?" + q, timeout=600).read()
        with open(out, "wb") as f: f.write(data)
        print("SAVED", out, len(data), flush=True)

if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else "ref"
    if mode == "ref":
        pt = open("/home/zyw/h3job/prompt_ref2va_v9.txt").read()
        p = graph_ref(pt); out = "/home/zyw/h3job/ref2va_v9.mp4"
    elif mode == "fun":
        pt = open("/home/zyw/h3job/prompt_funcontrol_v9.txt").read()
        p = graph_fun(pt); out = "/home/zyw/h3job/funcontrol_v9.mp4"
    else:
        raise SystemExit("mode ref|fun")
    pid = submit(p, mode)
    item = wait(pid)
    download(item, out)
