#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""B route: refine the cached 294-frame first-pass latent at 768P by splitting it into
overlapping chunks (LatentSplit 136/17), re-sampling each chunk with 3-step sigmas,
then concatenating and decoding (H3 AV).

Usage: python b_refine_chunks.py [--one-chunk]
"""
import json, sys, time, uuid
from pathlib import Path
import requests

BASE = "http://192.168.31.31:8189"
S = requests.Session(); S.trust_env = False
HERE = Path(__file__).resolve().parent

W, H = 1376, 768
FRAMES = 294
SEED = 20261031
REF1 = "head_turnaround.jpg"
REF2 = "body_turnaround.jpg"

PROMPT_TEXT = (HERE / "prompt.txt").read_text(encoding="utf-8")

P = {
    "1": {"class_type": "H3CacheLatentLoader", "inputs": {
        "latent_path": "minimax_seg_cache/10/seg_0000.av.pt"}},
    "2": {"class_type": "MiniMaxH3AVLatentSeparateT8", "inputs": {"av_latent": ["1", 0]}},
    "3": {"class_type": "AICG3D_H3LatentUpscaler3D", "inputs": {
        "latent": ["2", 0],
        "model_name": "minimax_h3_latent_upscaler_3d_bf16.safetensors",
        "mode": "target dimensions", "mode.width": W, "mode.height": H,
        "align": 32, "enable_chunking": True, "device": "cuda", "precision": "fp16"}},
    "4": {"class_type": "MiniMaxH3AVLatentBuilderT8Advanced", "inputs": {
        "video_latent": ["3", 0], "audio_latent": ["2", 1]}},
    "5": {"class_type": "CLIPLoader", "inputs": {
        "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors", "type": "minimax", "device": "default"}},
    "6": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_video_vae_fp16.safetensors"}},
    "7": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_audio_vae_fp32.safetensors"}},
    "8": {"class_type": "LoadImage", "inputs": {"image": REF1}},
    "9": {"class_type": "LoadImage", "inputs": {"image": REF2}},
    "10": {"class_type": "MiniMaxH3ReferenceToVideo", "inputs": {
        "clip": ["5", 0], "prompt": PROMPT_TEXT, "width": W, "height": H, "length": FRAMES,
        "ref_image_size": "match", "vae": ["6", 0], "audio_vae": ["7", 0],
        "ref_images.ref_image_0": ["8", 0], "ref_images.ref_image_1": ["9", 0]}},
    "11": {"class_type": "MiniMaxH3LatentSplit", "inputs": {
        "latent": ["4", 0], "chunk_length": 136, "overlap": 17,
        "resize_conditioning": False, "conditioning": ["10", 0]}},
    "20": {"class_type": "UNETLoader", "inputs": {
        "unet_name": "minimax_h3_ref2va_pruned_w4a8_mixed.safetensors", "weight_dtype": "default"}},
    "21": {"class_type": "LoraLoaderModelOnly", "inputs": {
        "model": ["20", 0],
        "lora_name": "minimax_h3_fl2v_turbo_4step_v1.0_768p_comfyui_bf16.safetensors",
        "strength_model": 1.0}},
    "22": {"class_type": "BasicScheduler", "inputs": {
        "scheduler": "beta", "steps": 3, "denoise": 0.25, "model": ["21", 0]}},
    "23": {"class_type": "RandomNoise", "inputs": {"noise_seed": SEED}},
    "24": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "euler"}},
    "30": {"class_type": "MiniMaxH3AVDecodeT8", "inputs": {
        "av_latent": ["40", 0], "video_vae": ["6", 0], "audio_vae": ["7", 0]}},
    "41": {"class_type": "CreateVideo", "inputs": {
        "images": ["30", 0], "audio": ["30", 1], "fps": 24.0, "bit_depth": 8}},
    "42": {"class_type": "SaveVideo", "inputs": {
        "video": ["41", 0], "filename_prefix": "video/h3_b_refine", "format": "auto", "codec": "auto"}},
}

one_chunk = "--one-chunk" in sys.argv
chunks = 3 if not one_chunk else 1
outs = []
for i in range(chunks):
    fid = f"5{i}"
    P[fid] = {"class_type": "MiniMaxH3LatentFromBatch", "inputs": {
        "latents": ["11", 0], "cond_batch": ["11", 1], "segments": ["11", 2], "index": i}}
    sid = f"7{i}"
    gid = f"6{i}"
    P[gid] = {"class_type": "BasicGuider", "inputs": {
        "model": ["21", 0], "conditioning": [fid, 1]}}
    P[sid] = {"class_type": "SamplerCustomAdvanced", "inputs": {
        "noise": ["23", 0], "guider": [gid, 0], "sampler": ["24", 0],
        "sigmas": ["22", 0], "latent_image": [fid, 0]}}
    outs.append([sid, 0])

concat_inputs = {f"segments.segment_{i}": o for i, o in enumerate(outs)}
concat_inputs["segments_info"] = ["11", 2]
P["40"] = {"class_type": "MiniMaxH3ConcatLatents", "inputs": concat_inputs}

r = S.post(f"{BASE}/prompt", json={"prompt": P, "client_id": str(uuid.uuid4())}, timeout=120)
print("[submit]", r.status_code, r.text[:2000])
r.raise_for_status()
pid = r.json()["prompt_id"]
t0 = time.time()
while time.time() - t0 < 6 * 3600:
    h = S.get(f"{BASE}/history/{pid}", timeout=60).json()
    if pid in h:
        e = h[pid]; st = e.get("status", {})
        print("[status]", st.get("status_str"), f"{int(time.time()-t0)}s")
        if st.get("status_str") == "error":
            print(json.dumps(st, ensure_ascii=False)[:3000])
        files = []
        for nid, o in (e.get("outputs") or {}).items():
            for key in ("images", "gifs", "videos"):
                for it in (o.get(key) or []):
                    if isinstance(it, dict) and it.get("filename"):
                        files.append(it)
        print("[outputs]", files)
        for it in files:
            if it["filename"].lower().endswith(".mp4"):
                rr = S.get(f"{BASE}/view", params={"filename": it["filename"], "subfolder": it.get("subfolder", ""), "type": it.get("type", "output")}, timeout=900)
                rr.raise_for_status()
                dest = HERE / "checks20" / ("h3_b_refine_one.mp4" if one_chunk else "h3_b_refine_full.mp4")
                dest.parent.mkdir(exist_ok=True)
                dest.write_bytes(rr.content)
                print("[saved]", dest, f"{len(rr.content)/1e6:.1f} MB")
                break
        break
    print(f"[poll] {int(time.time()-t0)}s", flush=True)
    time.sleep(15)
