#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Phase-1 smoke test: load cached first-pass AV latent -> H3 3D latent upscale -> AV decode -> save."""
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

PROMPT = {
    "1": {"class_type": "H3CacheLatentLoader", "inputs": {
        "latent_path": "minimax_seg_cache/10/seg_0000.av.pt"}},
    "2": {"class_type": "AICG3D_H3LatentUpscaler3D", "inputs": {
        "latent": ["1", 0],
        "model_name": "minimax_h3_latent_upscaler_3d_bf16.safetensors",
        "mode": "target dimensions",
        "mode.width": 1376,
        "mode.height": 768,
        "align": 32,
        "enable_chunking": True,
        "device": "cuda",
        "precision": "fp16"}},
    "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"}},
    "3": {"class_type": "MiniMaxH3AVDecodeT8", "inputs": {
        "av_latent": ["2", 0], "video_vae": ["6", 0], "audio_vae": ["7", 0]}},
    "4": {"class_type": "CreateVideo", "inputs": {
        "images": ["3", 0], "audio": ["3", 1], "fps": 24.0, "bit_depth": 8}},
    "5": {"class_type": "SaveVideo", "inputs": {
        "video": ["4", 0], "filename_prefix": "video/h3_up_test", "format": "auto", "codec": "auto"}},
}

r = S.post(f"{BASE}/prompt", json={"prompt": PROMPT, "client_id": str(uuid.uuid4())}, timeout=120)
print("[submit]", r.status_code, r.text[:1500])
r.raise_for_status()
pid = r.json()["prompt_id"]
t0 = time.time()
while time.time() - t0 < 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])
        outs = []
        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"):
                        outs.append(it)
        print("[outputs]", outs)
        for it in outs:
            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_upscale_test.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(10)
