#!/usr/bin/env python3
"""
批量用 H3 Turbo 快速预览生成 8 个 validation case。
用 requests 库处理 multipart upload。
"""
import os, sys, time, json, subprocess, requests

KAP = "http://localhost:10588"
BASE = "/home/kai/文档/LTX/validition_v1"
OUT = "/home/kai/shared/validation_preview"
os.makedirs(OUT, exist_ok=True)

CASES = [
    ("01", "1.jpg", "16:9", 8),
    ("02", "1.jpg", "16:9", 8),
    ("03", "01.png", "9:16", 8),
    ("04", "01.png", "16:9", 8),
    ("05", "1.png", "16:9", 8),
    ("06", "1.png", "9:16", 8),
    ("07", "1.jpg", "16:9", 8),
    ("08", "1.jpg", "16:9", 8),
]

def read_prompt(case_dir):
    p = os.path.join(BASE, case_dir, "prompt.txt")
    with open(p, "r") as f:
        return f.read().strip()

def submit_i2va(case_num, ff_path, prompt, aspect, duration):
    """Submit to KAP i2va API with turbo=true"""
    data = {
        "prompt": prompt[:800],
        "projectId": "999",
        "turbo": "true",
        "aspectRatio": aspect,
        "duration": str(duration),
        "steps": "4",
    }
    with open(ff_path, "rb") as f:
        files = {"firstFrame": (os.path.basename(ff_path), f, "image/jpeg")}
        resp = requests.post(f"{KAP}/api/production/minimax-h3/i2va", data=data, files=files, timeout=60)
    return resp.json()

def poll_status(prompt_id, label, timeout=600):
    start = time.time()
    while time.time() - start < timeout:
        try:
            resp = requests.get(f"{KAP}/api/production/minimax-h3/status/{prompt_id}", timeout=15)
            d = resp.json()
            data = d.get("data", d)
            status = data.get("status", "")
            if status in ("success", "completed"):
                print(f"✅ {label} DONE ({time.time()-start:.0f}s)", flush=True)
                return data
            elif status == "error":
                print(f"❌ {label} ERROR: {json.dumps(data)[:300]}", flush=True)
                return None
            elapsed = int(time.time() - start)
            if elapsed % 30 == 0 and elapsed > 0:
                print(f"  ⏳ {label} {elapsed}s... ({status})", flush=True)
        except Exception as e:
            print(f"  poll err {label}: {e}", flush=True)
        time.sleep(5)
    print(f"❌ {label} TIMEOUT", flush=True)
    return None

results = []
for case_num, ff_file, aspect, duration in CASES:
    case_dir = os.path.join(BASE, case_num)
    ff_path = os.path.join(case_dir, ff_file)
    prompt = read_prompt(case_dir)
    
    print(f"\n{'='*50}", flush=True)
    print(f"[{time.strftime('%H:%M:%S')}] Case {case_num}: submitting H3 Turbo i2va...", flush=True)
    
    try:
        resp = submit_i2va(case_num, ff_path, prompt, aspect, duration)
        data = resp.get("data", resp)
        prompt_id = data.get("promptId", data.get("prompt_id", ""))
        print(f"  promptId: {prompt_id}", flush=True)
        
        if not prompt_id:
            print(f"  ⚠️ No promptId: {json.dumps(resp)[:400]}", flush=True)
            results.append({"case": case_num, "status": "error"})
            continue
        
        result_data = poll_status(prompt_id, f"Case {case_num}", timeout=600)
        
        if result_data:
            video_url = None
            videos = result_data.get("videos", [])
            if isinstance(videos, list) and videos:
                v0 = videos[0]
                video_url = v0.get("url", v0.get("path", "")) if isinstance(v0, dict) else str(v0)
            elif isinstance(videos, str):
                video_url = videos
            if not video_url:
                outputs = result_data.get("outputs", {})
                if isinstance(outputs, dict):
                    for v in outputs.values():
                        if isinstance(v, list) and v:
                            video_url = v[0].get("url", v[0].get("filename", "")) if isinstance(v[0], dict) else str(v[0])
                            break
                        elif isinstance(v, dict):
                            video_url = v.get("url", v.get("filename", ""))
                            break
            
            if video_url:
                # Fix URL if relative
                if video_url.startswith("/"):
                    video_url = f"http://localhost:8188{video_url}"
                local = os.path.join(OUT, f"case{case_num}_h3turbo.mp4")
                subprocess.run(["curl", "-sL", "-o", local, video_url], check=True, timeout=120)
                sz = os.path.getsize(local) // 1024
                print(f"  📥 Downloaded: case{case_num}_h3turbo.mp4 ({sz}KB)", flush=True)
                results.append({"case": case_num, "status": "ok", "path": local, "size_kb": sz})
            else:
                print(f"  ⚠️ No video URL: {json.dumps(result_data)[:400]}", flush=True)
                results.append({"case": case_num, "status": "no_video"})
        else:
            results.append({"case": case_num, "status": "failed"})
            
    except Exception as e:
        print(f"  ❌ Case {case_num} exception: {e}", flush=True)
        results.append({"case": case_num, "status": "error", "error": str(e)})

print(f"\n{'='*50}", flush=True)
print("RESULTS:", flush=True)
for r in results:
    print(f"  Case {r['case']}: {r['status']} {r.get('path','')}", flush=True)
print("ALL_DONE", flush=True)
