#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""KDA 神之八秒 challenge: rv2v (source video + 3 character refs), 4-step + refine upscale -> 1344x768.

Reference: Douyin aweme 7700170778671284691 (朵妈学AI, white-mannequin dance, 12.13 s)
Target  : the CG girl from the character sheets performs the same dance, same studio/camera/cuts.
Audio   : source video audio (timeline output.audioMode = "source").
"""
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"
PREP = REF / "prep"

# ---------------- generation parameters ----------------
W1, H1 = 864, 480          # first pass canvas (official rv2v default, 16:9)
W2, H2 = 1344, 768         # refine / final canvas (768P landscape)
FRAMES = 260               # 11.083 s @ 24 fps  (17k+5)
FPS = 24.0
SEED = 20261031
STEPS = 4                  # 4-step turbo first pass

VIDEO = REF / "source_288f_864x486_24fps.mp4"
PIC1 = PREP / "pic1_front.jpg"
PIC2 = PREP / "pic2_face_front.jpg"
PIC3 = PREP / "pic2_full.jpg"

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

PROMPT = """subject_definitions:
<Subject 1> is the single girl defined by <Picture 1>, <Picture 2> and <Picture 3>: a slender young woman with pale porcelain skin, a soft heart-shaped face, large warm brown eyes with fine lashes, rosy cheeks, a small nose and soft pink lips; light ash-brown hair with a straight full fringe and two long braids falling in front of her shoulders, with small red flower clips above her right temple and at the roots of both braids; she wears a pale-pink one-piece swimsuit with thin shoulder straps, a slightly deeper pink trim and a high-cut leg; she is barefoot.
<Picture 1> is the full-body front view of <Subject 1> and is the identity, costume and body-proportion anchor: her face, braid length, swimsuit cut and trim colour and her proportions must match it exactly.
<Picture 2> is the close-up front view of <Subject 1>'s face and is the anchor for her eyes, fringe, cheeks and the braid roots.
<Picture 3> is a character turnaround sheet of the SAME single girl seen from front, side and back; its three figures are one person, never three people, and it supplies her side profile, the back of her head with the two braids, and the fit of the swimsuit.
<Subject 2> is the dance performance in <Video 1>: the exact order and timing of every arm sweep, hand push toward the lens, shoulder roll, waist bend, leg extension, high kick, step and final pose, together with the shot-by-shot framing and cut rhythm. Only the movement and camera grammar are reused; the white mannequin's bald head, white skin, white cropped top, white shorts and faceless look are not reused.
<Subject 3> is the studio environment in <Video 1>: a seamless light-grey cyclorama, a pale glossy floor with soft reflections, and a large soft key light from the upper left with gentle fill.

summary:
[video editing + reference generation] The target video is an edited version of <Video 1>: the white mannequin is replaced by <Subject 1> taken from the three pictures, while every shot, cut, lens and dance beat of <Video 1> is preserved; she performs <Subject 2> inside the studio of <Subject 3>, rendered as a polished 3D CG character.

retention_analysis:
<Subject 1> (appears in every shot): fully_preserved - the same face, ash-brown fringe and twin braids with red flower clips, the same pale-pink one-piece swimsuit, and the same slender proportions in every shot.
<Picture 1> (identity and costume anchor): fully_preserved - face, hair, swimsuit and body proportions stay identical.
<Picture 2> (face anchor): fully_preserved - eye shape, fringe parting, cheek blush and braid roots stay identical in every close-up.
<Picture 3> (side and back anchor): partially_preserved - it is used for the side profile and the back of the head; the three drawn figures are the same person and never appear together.
<Subject 2> (appears in every shot): fully_preserved - each gesture, step, kick and pose follows the same order and timing as <Video 1>.
<Subject 3> (appears in every shot): fully_preserved - the same seamless grey backdrop, glossy floor, soft key light and gentle falloff.
<Video 1> (shot list, cut timing and camera): fully_preserved - the same shots in the same order at the same times, with no added or removed shots.

detailed_description:
The target video is a polished 3D CG character render with soft studio lighting, gentle skin sheen, fine individual hair strands, shallow depth of field and a clean, slightly cool white balance.
[Shot 1] 0.00s-2.60s. Three quick setups cut on the beat inside <Subject 3>. First a wide full-body shot from knee height: <Subject 1> stands barefoot on the glossy floor, arms relaxed, then sweeps her right arm out to the side and across her chest while her left hand rises to shoulder height. Then a medium waist-up shot: her right arm crosses in front of her face, palm open, and her head tilts down and to her left. Then a tight close-up: her face turns down, eyes lowered, the fringe falling over her brow. Soft key light from the upper left models her cheek and shoulder; the background stays an unbroken pale grey.
[Shot 2] At 00:02.600, the shot cuts to an extreme close-up on an 18mm wide-angle lens. Both of <Subject 1>'s hands push toward the lens and frame her face, the near hand large and softly out of focus, her eyes looking past the fingers. Strong wide-angle distortion, the studio behind her stretched and blurred, a faint bloom around the ceiling light; her braids swing forward with the motion.
[Shot 3] At 00:03.950, the shot cuts to a wide full-body shot. She balances on her left foot and extends her right leg back and up into an arabesque, arms opening wide, back arched, then lowers the leg and settles.
[Shot 4] At 00:04.900, a wide full-body shot: she lifts both arms overhead, wrists together, rises onto the balls of her feet, then steps forward and swings her arms down and across, hips and shoulders counter-rotating.
[Shot 5] At 00:06.350, a medium shot from her right side: she turns into profile, chin lifted, one arm extended forward at shoulder height, the other trailing behind; the braids and the swimsuit trim move with her.
[Shot 6] At 00:07.350, a wide full-body shot: she kicks her right leg high in front of her, arms raised, then plants the foot and coils for the next beat.
[Shot 7] At 00:08.300, a medium shot: she crosses both forearms in front of her chest, then lifts them above her head, elbows bent, head dipping under her arms.
[Shot 8] At 00:09.200, a wide full-body shot: she steps sideways, points her right arm out to the side and rolls her hips, weight shifting from foot to foot.
[Shot 9] At 00:10.400, a close-up: her face fills the frame, she looks straight into the lens and gives a faint closed-mouth smile, one hand rising near her cheek; the background dissolves into soft grey bokeh.
Every cut lands on the same beat as <Video 1>, and her feet stay planted on the same floor marks without sliding or floating.

overall_soundscape:
A quiet acoustically dry studio room tone, soft barefoot steps on the glossy floor, a light rustle of the swimsuit fabric and quiet breathing; the sounds stay low and close.

non_diegetic_music:
A confident K-pop dance track at about 110 BPM: a punchy synth bass, sharp handclaps on the backbeat, short brass-like stabs and a bright female vocal chant, with the cuts landing on the beat.
"""


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": False,
            "continuityOverlapFrames": 9,
            "audioMode": "source",
        },
        "gen": {"defaultFrameCount": FRAMES},
        "segments": [{
            "id": "s0",
            "start": 0,
            "length": FRAMES,
            "frameCount": FRAMES,
            "durationSec": round(FRAMES / FPS, 3),
            "prompt": PROMPT,
            "taskType": TASK_TYPE,
            **common,
        }],
        "runSelectEnabled": False,
        "runSelection": [],
    }


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"}},
        "2": {"class_type": "LoraLoaderModelOnly", "inputs": {
            "model": ["1", 0],
            "lora_name": "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors",
            "strength_model": 1.0}},
        # second-pass model chain: ref2va w4a8 + 768p 4-step turbo lora (official 二采 recipe)
        "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}},
        "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": "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": "16:9 (宽屏)",
            "megapixels": round(W2 * H2 / 1e6, 3),
            "width": W2,
            "height": H2,
            "skip_fl2v": True,
            "confirm_first_pass": False,
            "enable_latent_chunking": True,
            "enable_tiling": False,
            "tile_count": 2,
            "tile_overlap": 128}},
        "10": {"class_type": "ComfyMiniMaxH3Director", "inputs": {
            "model": ["2", 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),
            "refine": ["9", 0],
            "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,
            "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_kda_8s",
            "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 collect(entry):
    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)
    return files


def main():
    dry = "--dry-run" in sys.argv
    no_refine = "--no-refine" in sys.argv
    vname = upload(VIDEO, video=True)
    names = [upload(PIC1), upload(PIC2), upload(PIC3)]
    prompt = build_prompt(vname, names)
    if no_refine:
        prompt.pop("9", None)
        prompt.pop("8", None)
        prompt.pop("3", None)
        prompt.pop("4", None)
        prompt["10"]["inputs"].pop("refine", None)
        prompt["12"]["inputs"]["filename_prefix"] = "video/h3_kda_firstpass"
    (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}\nfinal={W2}x{H2}\nframes={FRAMES} fps={FPS} "
        f"({FRAMES/FPS:.3f}s)\nworkflow=official Director rv2v + Refine upscale (4-step turbo, audio=source)\n",
        encoding="utf-8")
    if dry:
        print("[dry-run] prompt built, not submitted")
        return
    pid = submit(prompt)
    (OUT_DIR / "prompt_id.txt").write_text(pid, encoding="utf-8")
    entry = wait(pid)
    files = collect(entry)
    print("[outputs]", files)
    (OUT_DIR / "history_entry.json").write_text(json.dumps(entry, ensure_ascii=False, indent=1), encoding="utf-8")
    if not files:
        print("no output files"); sys.exit(2)
    dest = OUT_DIR / "20261031_KDA神之八秒_粉泳装_4步放大768P.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()
