#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""T2VA (text to video+audio) via official MiniMax H3 Director on GPU box."""
import json, sys, time, uuid, urllib.request, urllib.parse
BASE = "http://192.168.31.31:8189"
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
PROMPT = open('prompt.txt', encoding='utf-8').read().strip()
FRAMES, FPS, SEED = 243, 24.0, 20261029
W1, H1 = 864, 480
W2, H2 = 1376, 768

timeline = {
    "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": "t2v — 文生视频(Text to Video)", "prompt": PROMPT, "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": "t2v — 文生视频(Text to Video)", "refs": [], "refAudios": [],
                  "refVideos": [], "referenceVideo": {}, "genImage": {"imageFile": ""}}],
    "runSelectEnabled": False, "runSelection": [],
}

graph = {
  "1": {"class_type": "UNETLoader", "inputs": {"unet_name": "minimax_h3_fl2va_pruned_int8_convrot.safetensors", "weight_dtype": "default"}},
  "2": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["1",0], "lora_name": "minimax_h3_fl2v_turbo_4step_v1.0_768p_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": "t2v — 文生视频(Text 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(timeline, 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": "video/h3_t2v_autumn_river_v3", "format": "auto", "codec": "auto"}},
}

json.dump(graph, open('api_prompt.json','w',encoding='utf-8'), ensure_ascii=False, indent=1)
body = json.dumps({"prompt": graph, "client_id": str(uuid.uuid4())}).encode()
req = urllib.request.Request(BASE+"/prompt", data=body, headers={"Content-Type":"application/json"})
try:
    with opener.open(req, timeout=120) as r: data = json.load(r)
except urllib.error.HTTPError as e:
    print("REJECTED", e.code, e.read().decode()[:2000]); sys.exit(1)
pid = data["prompt_id"]; print("submitted", pid, flush=True)
open('prompt_id.txt','w').write(pid)
t0 = time.time(); last=""
while True:
    try:
        with opener.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(20); 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)
        json.dump(rec, open('history_entry.json','w',encoding='utf-8'), ensure_ascii=False, indent=1)
        if st.get("completed") or st.get("status_str") in ("error","failed"): break
    else:
        line=f"{int(time.time()-t0)}s queued"
        if line!=last: print(line, flush=True); last=line
    time.sleep(20)

files=[]
for _n,o in (rec.get("outputs") or {}).items():
    for k in ("images","videos","gifs"):
        for it in (o.get(k) or []):
            if isinstance(it,dict) and it.get("filename"): files.append(it)
print("outputs", files, flush=True)
for it in files:
    if it["filename"].lower().endswith((".mp4",".webm",".mov")):
        q = urllib.parse.urlencode({"filename":it["filename"],"subfolder":it.get("subfolder",""),"type":it.get("type","output")})
        with opener.open(f"{BASE}/view?{q}", timeout=1800) as r, open("raw_"+it["filename"],"wb") as f:
            f.write(r.read())
        print("saved raw_"+it["filename"], flush=True)
        break
