# -*- coding: utf-8 -*-
import json, sys, time, uuid, urllib.request, urllib.parse, os
BASE="http://192.168.31.31:8189"
op=urllib.request.build_opener(urllib.request.ProxyHandler({}))
REFS=['ref_face.png','ref_body.png','ref_scene.png']
W1,H1,W2,H2=864,480,1408,800
FPS=24.0
SHOTS=[('s1',141),('s2',141),('s3',192),('s4',175),('s5',158),('s6',124)]

def graph_for(shot, frames, prompt, seed):
    refs=[{"index":i,"imageFile":n,"fileName":"","type":"input","subfolder":""} for i,n in enumerate(REFS)]
    tl={"version":5,"editMode":"segment","timelineMode":"gen_blank","totalFrames":frames,"frameRate":FPS,
     "width":W1,"height":H1,"refMaxSize":864,
     "video":{"fileName":"","videoFile":"","subfolder":"","type":"input","frames":[]},"videoClips":[],
     "global":{"taskType":"r2v — 参考主体生视频(Reference to Video)","prompt":prompt,"refs":refs,
       "refVideos":[],"referenceVideo":{},"continuousReference":False,"commonEnabled":False,
       "genImage":{"imageFile":""}},
     "output":{"mode":"fixed","aspectRatio":"16:9 (宽屏)","megapixels":round(W1*H1/1e6,3),"multiple":32,
       "longEdge":max(W1,H1),"width":W1,"height":H1,"maxExportFrames":0,"exportMode":"all",
       "continuityEnabled":False,"continuityOverlapFrames":9},
     "gen":{"defaultFrameCount":frames},
     "segments":[{"id":"seg0","start":0,"length":frames,"frameCount":frames,"durationSec":round(frames/FPS,3),
       "prompt":prompt,"negativePrompt":"","taskType":"r2v — 参考主体生视频(Reference to Video)",
       "refs":refs,"refAudios":[],"refVideos":[],"referenceVideo":{},"genImage":{"imageFile":""}}],
     "runSelectEnabled":False,"runSelection":[]}
    return {
     "1":{"class_type":"UNETLoader","inputs":{"unet_name":"minimax_h3_ref2va_pruned_int8_convrot.safetensors","weight_dtype":"default"}},
     "2":{"class_type":"LoraLoaderModelOnly","inputs":{"model":["1",0],"lora_name":"minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors","strength_model":1.0}},
     "3":{"class_type":"CLIPLoader","inputs":{"clip_name":"qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","type":"minimax","device":"default"}},
     "4":{"class_type":"VAELoader","inputs":{"vae_name":"minimax_h3_video_vae_fp16.safetensors"}},
     "5":{"class_type":"VAELoader","inputs":{"vae_name":"minimax_h3_audio_vae_fp32.safetensors"}},
     "6":{"class_type":"BasicScheduler","inputs":{"scheduler":"beta","steps":3,"denoise":0.2,"model":["2",0]}},
     "7":{"class_type":"MiniMaxH3DirectorRefine","inputs":{"mode":"upscale","upscale_method":"h3_latent",
       "latent_upscale_model":"minimax_h3_latent_upscaler_3d_bf16.safetensors","sampler":"euler","passes":1,
       "refine_model":["2",0],"sigmas":["6",0],"seed_mode":"inherit","aspect_ratio":"16:9 (宽屏)",
       "megapixels":round(W2*H2/1e6,3),"width":W2,"height":H2,"skip_fl2v":True,"confirm_first_pass":False,
       "enable_latent_chunking":False,"enable_tiling":False,"tile_count":2,"tile_overlap":128}},
     "8":{"class_type":"ComfyMiniMaxH3Director","inputs":{"model":["2",0],"video_vae":["4",0],"audio_vae":["5",0],
       "clip":["3",0],"task_type":"r2v — 参考主体生视频(Reference to Video)","global_prompt":prompt,
       "bd_grp_sample":"采样设置","bd_grp_advanced":"高级采样","bd_grp_perf":"性能","cfg":1.0,"seed":seed,
       "frame_rate":FPS,"width":W1,"height":H1,"ref_max_size":864,"total_frames":frames,
       "timeline_data":json.dumps(tl,ensure_ascii=False),"refine":["7",0],"steps":4,
       "sampler":"res_multistep","scheduler":"simple","shift_video":12.0,"shift_audio":3.0,
       "clear_vram_between_segments":True,"clear_vram_before_refine":True,"export_source_images":False}},
     "9":{"class_type":"CreateVideo","inputs":{"images":["8",0],"audio":["8",1],"fps":["8",2],"bit_depth":8}},
     "10":{"class_type":"SaveVideo","inputs":{"video":["9",0],"filename_prefix":f"video/h3_r2v_40s_{shot}","format":"auto","codec":"auto"}},
    }

def submit(graph):
    body=json.dumps({"prompt":graph,"client_id":str(uuid.uuid4())}).encode()
    req=urllib.request.Request(BASE+"/prompt",data=body,headers={"Content-Type":"application/json"})
    with op.open(req,timeout=120) as r: return json.load(r)["prompt_id"]

def wait(pid):
    t0=time.time()
    while True:
        try:
            with op.open(f"{BASE}/history/{pid}",timeout=60) as r: h=json.load(r)
        except Exception as e:
            print("  poll err",e,flush=True); time.sleep(25); continue
        if pid in h:
            rec=h[pid]; st=rec.get("status",{})
            print("  status",st.get("status_str"),st.get("completed"),f"{int(time.time()-t0)}s",flush=True)
            if st.get("completed") or st.get("status_str") in ("error","failed"): return rec
        time.sleep(20)

def download(rec, shot):
    for _n,o in (rec.get("outputs") or {}).items():
        for it in (o.get("images") or [])+(o.get("videos") or []):
            fn=it.get("filename","")
            if isinstance(it,dict) and fn.lower().endswith((".mp4",".webm")):
                q=urllib.parse.urlencode({"filename":fn,"subfolder":it.get("subfolder",""),"type":it.get("type","output")})
                out=f"shot_{shot}.mp4"
                with op.open(f"{BASE}/view?{q}",timeout=1800) as r, open(out,"wb") as f: f.write(r.read())
                print("  saved",out,flush=True); return out
    return None

only = sys.argv[1:] or [s for s,_ in SHOTS]
for shot, frames in SHOTS:
    if shot not in only: continue
    prompt=open(f"prompt_{shot}.txt",encoding='utf-8').read().strip()
    seed=20261029
    print(f"=== {shot} frames={frames} ===",flush=True)
    try:
        pid=submit(graph_for(shot,frames,prompt,seed)); print("  pid",pid,flush=True)
        open(f"pid_{shot}.txt","w").write(pid)
        rec=wait(pid)
        json.dump(rec,open(f"history_{shot}.json","w",encoding='utf-8'),ensure_ascii=False,indent=1)
        download(rec,shot)
    except Exception as e:
        print("  ERROR",e,flush=True)
print("ALL DONE",flush=True)
