#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""KDA 神之八秒 challenge, ANIME version: rv2v with two full turnaround sheets (head + body),
no cropping. First pass only (864x480, 4-step turbo, 260 frames); Real-ESRGAN upscale afterwards.
"""
import json
import sys
import time
import uuid
from pathlib import Path

import requests

GPU = "192.168.31.31"
PORT = 8189
BASE = f"http://{GPU}:{PORT}"
S = requests.Session()
S.trust_env = False

HERE = Path(__file__).resolve().parent
OUT_DIR = HERE
REF = HERE / "ref"

W1, H1 = 480, 864
FRAMES = 600
SEG = 120
FPS = 24.0
SEED = 20261101
import sys as _sys
_idx = None
for _a in _sys.argv:
    if _a.startswith("--index="):
        _idx = int(_a.split("=",1)[1])
RUN_SELECT = _idx is not None
RUN_SELECTION = [_idx] if _idx is not None else []
STEPS = 20

VIDEO = REF / "source_600f_480x864_24fps.mp4"
PIC1 = REF / "head_turnaround.jpg"
PIC2 = REF / "body_turnaround.jpg"

TASK_TYPE = "rv2v — 参考素材改视频(Reference Video Edit)"

PROMPT = """subject_definitions:
<Subject 1> is the anime girl defined by <Picture 1> and <Picture 2>. <Picture 1> is a head turnaround sheet of the SAME single girl drawn three times (front, side, back) - the three heads are one person, never three people; it anchors her face: large rose-red eyes with dark lashes, thin arched brows, a small nose, a gentle closed-mouth smile, pale skin with a soft blush, long wavy pale-blonde hair with a centre part and face-framing strands falling past her waist, and a pearl-and-flower hair clip on the right side of her head. <Picture 2> is a full-body turnaround sheet of the SAME single girl in the same three angles - the three bodies are one person, never a group; it anchors her proportions and outfit: a white cropped school blazer with gold buttons and a gold badge on the left chest, a navy-blue necktie, a white collared shirt, a high-waisted golden-yellow pleated skirt, white knee-high socks with a gold band and black lace-up heeled ankle boots. The turnaround sheets are reference only; they are never shown on screen.
<Video 1> is the source reference video for the target video edit. It supplies the movement of a blank white mannequin dancing alone in an empty grey studio: the exact choreography, camera framing, camera movement, body timing, and pacing. Its blank white plastic body, faceless head, and studio lighting are not part of the target video. The small text overlay at the bottom edge of <Video 1> is production watermarking; it is not referenced, must not be reproduced, and the target video contains no text at all.

summary:
[video editing + character replacement] Replace the white mannequin of <Video 1> with <Subject 1>, keeping the choreography, camera behaviour and timing of <Video 1> frame for frame. <Subject 1> is the only person on screen, dancing alone in the same empty light-grey studio.

detailed_description:
The target video is a single continuous 25-second shot, 9:16 vertical, 24 fps, 480x864. The backdrop is an empty light-grey cyclorama studio with a soft gradient, a plain floor with subtle reflections and no props, no furniture, no second person and no text. The camera is locked on a full-body vertical framing of the dancer, staying wide enough to keep her head and feet inside the frame, with the gentle push-ins and small reframes of <Video 1>.
<Subject 1> must be fully established as the same person as <Picture 1> and <Picture 2> at 0.00 seconds: same face, same pale-blonde wavy hair past the waist, same hair clip on the right side, same white cropped blazer with gold buttons and chest badge, navy necktie, white shirt, golden-yellow pleated skirt, white knee socks, black lace-up heeled ankle boots. Her rendering is clean cel-shaded anime with crisp lineart, soft gradient shading and a subtle rim light.
Motion, beat by beat, following <Video 1>: from 00:00 to 00:03 she stands with her weight on one leg and her right arm extended out to the side, palm open, swaying gently. From 00:03 to 00:06 she brings both hands up in front of her face as if in a small prayer, then opens both arms outward. From 00:06 to 00:09 she sweeps her arms overhead in wide arcs, one after the other, hips swaying with the beat. From 00:09 to 00:12 she raises one arm high above her head while the other crosses her chest, turning her shoulders slowly. From 00:12 to 00:15 she opens both arms out to the sides and takes small side steps, twisting her torso. From 00:15 to 00:18 she bends her elbows outward, elbows up, with quick shoulder isolations and a small head tilt. From 00:18 to 00:21 she lifts both arms overhead, arches her back slightly and raises one leg in a slow controlled extension. From 00:21 to 00:23 she spins on one foot with her arms out, her long hair swinging outward and settling. From 00:23 to 00:25 she slows down, plants both feet, and finishes with her arms opening toward the camera and a soft confident look.
The choreography is a smooth, continuous dance with no cuts, no camera shake, no zoom jumps, no morphing of the body, no extra limbs, no duplicated person, and no scene change. Feet stay on the floor except during the single-leg extension and the spin.

retention_analysis:
<Video 1>: choreography_fully_preserved. camera_fully_preserved. timing_fully_preserved. background_fully_preserved. overlay_text_not_referenced.
<Picture 1>: identity_fully_preserved, face_fully_referenced.
<Picture 2>: outfit_fully_referenced, proportions_fully_referenced.
<Subject 1>: identity_fully_preserved.

overall_soundscape:
Silent studio interior: no dialogue, no footsteps, no breathing, no fabric rustle, no room tone, no ambience whatsoever.

non_diegetic_music:
No music. Complete silence.
"""


def upload(path: Path, video: bool = False) -> str:
    with open(path, "rb") as f:
        r = S.post(f"{BASE}/upload/image",
                   files={"image": (path.name, f, "video/mp4" if video else "image/jpeg")},
                   data={"type": "input", "overwrite": "true"}, timeout=300)
    r.raise_for_status()
    j = r.json()
    name = j["name"]
    sub = j.get("subfolder") or ""
    print(f"[upload] {path.name} -> {sub + '/' if sub else ''}{name}")
    return name


def ref(name, index):
    return {"index": index, "imageFile": name, "fileName": name, "type": "input", "subfolder": ""}


def build_timeline(video_name, ref_names):
    seg_refs = [ref(n, i) for i, n in enumerate(ref_names)]
    common = {
        "taskType": TASK_TYPE,
        "negativePrompt": "",
        "refs": seg_refs,
        "refAudios": [],
        "refVideos": [],
        "referenceVideo": {},
        "genImage": {"imageFile": ""},
    }
    return {
        "version": 4,
        "editMode": "global",
        "timelineMode": "video",
        "totalFrames": FRAMES,
        "frameRate": FPS,
        "width": W1,
        "height": H1,
        "refMaxSize": 864,
        "video": {
            "fileName": video_name,
            "videoFile": video_name,
            "subfolder": "",
            "type": "input",
            "frames": [],
            "frameMap": [],
        },
        "videoClips": [],
        "global": {
            **common,
            "prompt": PROMPT,
            "continuousReference": False,
            "commonEnabled": False,
        },
        "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": True,
            "continuityOverlapFrames": 22,
            "audioMode": "source",
        },
        "gen": {"defaultFrameCount": SEG},
        "segments": [{
            "id": f"s{i}",
            "start": i * SEG,
            "length": SEG,
            "frameCount": SEG,
            "durationSec": round(SEG / FPS, 3),
            "prompt": PROMPT,
            "taskType": TASK_TYPE,
            **common,
        } for i in range(5)],
        "runSelectEnabled": RUN_SELECT,
        "runSelection": RUN_SELECTION,
    }


def build_prompt(video_name, ref_names):
    timeline = build_timeline(video_name, ref_names)
    return {
        "1": {"class_type": "UNETLoader", "inputs": {
            "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors", "weight_dtype": "default"}},
        "3": {"class_type": "UNETLoader", "inputs": {
            "unet_name": "minimax_h3_ref2va_pruned_w4a8_mixed.safetensors", "weight_dtype": "default"}},
        "4": {"class_type": "LoraLoaderModelOnly", "inputs": {
            "model": ["3", 0],
            "lora_name": "minimax_h3_fl2v_turbo_4step_v1.0_768p_comfyui_bf16.safetensors",
            "strength_model": 1.0}},
        "8": {"class_type": "BasicScheduler", "inputs": {
            "scheduler": "beta", "steps": 3, "denoise": 0.25, "model": ["4", 0]}},
        "9": {"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": ["4", 0],
            "sigmas": ["8", 0],
            "seed_mode": "inherit",
            "aspect_ratio": "9:16 (竖屏)",
            "megapixels": 1.032,
            "width": 768,
            "height": 1344,
            "skip_fl2v": True,
            "confirm_first_pass": False,
            "enable_latent_chunking": False,
            "enable_tiling": False,
            "tile_count": 2,
            "tile_overlap": 128}},
        "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"}},
        "10": {"class_type": "ComfyMiniMaxH3Director", "inputs": {
            "model": ["1", 0],
            "video_vae": ["6", 0],
            "audio_vae": ["7", 0],
            "clip": ["5", 0],
            "task_type": TASK_TYPE,
            "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),
            "steps": STEPS,
            "sampler": "res_multistep",
            "scheduler": "simple",
            "shift_video": 12.0,
            "shift_audio": 3.0,
            "clear_vram_between_segments": True,
            "clear_vram_before_refine": True,
            "refine": ["9", 0],
            "export_source_images": False}},
        "11": {"class_type": "CreateVideo", "inputs": {
            "images": ["10", 0], "audio": ["10", 1], "fps": ["10", 2], "bit_depth": 8}},
        "12": {"class_type": "SaveVideo", "inputs": {
            "video": ["11", 0], "filename_prefix": "video/h3_v2_ref",
            "format": "auto", "codec": "auto"}},
    }


def submit(prompt):
    cid = str(uuid.uuid4())
    r = S.post(f"{BASE}/prompt", json={"prompt": prompt, "client_id": cid}, timeout=120)
    print("[submit]", r.status_code, r.text[:1200])
    r.raise_for_status()
    return r.json()["prompt_id"]


def wait(pid, timeout=6 * 3600):
    t0 = time.time()
    last = ""
    while time.time() - t0 < timeout:
        try:
            h = S.get(f"{BASE}/history/{pid}", timeout=60).json()
        except Exception as exc:
            print("[poll] err", exc); time.sleep(15); continue
        if pid in h:
            e = h[pid]
            st = e.get("status", {})
            print("[status]", st.get("status_str"), st.get("completed"), f"{int(time.time()-t0)}s", flush=True)
            if st.get("status_str") == "error":
                print(json.dumps(st, ensure_ascii=False)[:4000])
            return e
        q = S.get(f"{BASE}/queue", timeout=30).json()
        run = len(q.get("queue_running", [])); pend = len(q.get("queue_pending", []))
        msg = f"[poll] {int(time.time()-t0)}s running={run} pending={pend}"
        if msg != last:
            print(msg, flush=True); last = msg
        time.sleep(20)
    raise TimeoutError("generation timeout")


def main():
    dry = "--dry-run" in sys.argv
    vname = VIDEO.name
    print(f"[skip-upload] reuse {vname}")
    names = [upload(PIC1), upload(PIC2)]
    prompt = build_prompt(vname, names)
    (OUT_DIR / "api_prompt.json").write_text(json.dumps(prompt, ensure_ascii=False, indent=1), encoding="utf-8")
    (OUT_DIR / "prompt.txt").write_text(PROMPT, encoding="utf-8")
    (OUT_DIR / "seed.txt").write_text(
        f"SEED={SEED}\nSTEPS={STEPS}\npass1={W1}x{H1}\nframes={FRAMES} fps={FPS} ({FRAMES/FPS:.3f}s)\n"
        f"workflow=official Director rv2v, 20 steps, native 768P (no turbo LoRA, no refine), 294f padded source\n",
        encoding="utf-8")
    if dry:
        print("[dry-run] prompt built")
        return
    pid = submit(prompt)
    (OUT_DIR / "prompt_id.txt").write_text(pid, encoding="utf-8")
    entry = wait(pid)
    files = []
    for nid, o in (entry.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)
    (OUT_DIR / "history_entry.json").write_text(json.dumps(entry, ensure_ascii=False, indent=1), encoding="utf-8")
    if not files:
        sys.exit(2)
    dest = OUT_DIR / "20261101_v2_768x1376_成片.mp4"
    for it in files:
        if not it["filename"].lower().endswith((".mp4", ".webm", ".mov")):
            continue
        r = S.get(f"{BASE}/view", params={"filename": it["filename"], "subfolder": it.get("subfolder", ""), "type": it.get("type", "output")}, timeout=1200)
        r.raise_for_status()
        dest.write_bytes(r.content)
        print("[saved]", dest, f"{len(r.content)/1e6:.1f} MB")
        break
    print("DONE", dest)


if __name__ == "__main__":
    main()
