import json, sys, time, urllib.request, urllib.parse, os
API="http://127.0.0.1:8189"
W,H,LEN,STEPS=544,960,90,4
SEED=20261020

def req(path,data=None):
    url=API+path
    if data is not None:
        r=urllib.request.Request(url,data=json.dumps(data).encode(),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 build(prompt, outfit, tag):
    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_post.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":outfit}}
    n["12"]={"class_type":"LoadImage","inputs":{"image":"hand_ref.png"}}
    n["13"]={"class_type":"LoadImage","inputs":{"image":"scene_clean.jpg"}}
    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}}
    n["20"]={"class_type":"MiniMaxH3ReferenceToVideo","inputs":{
        "clip":["2",0],"vae":["3",0],"audio_vae":["4",0],"prompt":prompt,
        "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_videos.ref_video_0":["6",0]}}
    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":["60",0],"scheduler":"simple","steps":STEPS,"denoise":1.0}}
    n["33"]={"class_type":"BasicGuider","inputs":{"model":["60",0],"conditioning":["20",0]}}
    n["34"]={"class_type":"SamplerCustomAdvanced","inputs":{"noise":["30",0],"guider":["33",0],"sampler":["31",0],"sigmas":["32",0],"latent_image":["20",1]}}
    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":24.0}}
    n["43"]={"class_type":"SaveVideo","inputs":{"video":["42",0],"filename_prefix":"h3_post_"+tag+"/wardrobe","format":"auto","codec":"auto"}}
    return n

def submit(p,tag):
    r=req("/prompt",{"prompt":p,"client_id":"dsh-post"})
    print("SUBMIT",tag,json.dumps(r)[:400],flush=True)
    if r.get("node_errors"):
        print(json.dumps(r["node_errors"],indent=2)[:4000]); raise SystemExit(2)
    return r["prompt_id"]

def wait(pid):
    t0=time.time()
    while True:
        h=req("/history/"+pid)
        if pid in h: return h[pid]
        print("wait",int(time.time()-t0),flush=True); time.sleep(8)

def download(item,out):
    for o in item.get("outputs",{}).values():
        for v in o.values():
            if isinstance(v,list):
                for it in v:
                    if isinstance(it,dict) and it.get("filename") and it.get("type")=="output":
                        q=urllib.parse.urlencode({"filename":it["filename"],"subfolder":it.get("subfolder",""),"type":"output"})
                        data=urllib.request.urlopen(API+"/view?"+q,timeout=600).read()
                        open(out,"wb").write(data); print("SAVED",out,len(data),flush=True)

if __name__=="__main__":
    mode=sys.argv[1]
    if mode=="A":
        pt=open("/home/zyw/h3job/post_A5.txt").read(); outfit="heels_front.jpg"; tag="A5"; out="/home/zyw/h3job/post_A5.mp4"
    elif mode=="B":
        pt=open("/home/zyw/h3job/post_B5.txt").read(); outfit="post_black_front.jpg"; tag="B5"; out="/home/zyw/h3job/post_B5.mp4"
    elif mode=="C":
        pt=open("/home/zyw/h3job/post_C5.txt").read(); outfit="post_C_front.jpg"; tag="C5"; out="/home/zyw/h3job/post_C5.mp4"
    else:
        pt=open("/home/zyw/h3job/post_D5.txt").read(); outfit="post_D_front.jpg"; tag="D5"; out="/home/zyw/h3job/post_D5.mp4"
    pid=submit(build(pt,outfit,tag),tag); item=wait(pid); download(item,out)
