#!/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 = 864, 480
FRAMES = 260
FPS = 24.0
SEED = 20261031
STEPS = 4

VIDEO = REF / "source_288f_864x486_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, a white strap garter on her left thigh, and white knee-high boots with gold trim and dark soles.
<Picture 1> is the identity anchor for her face, hair colour, hairstyle and the pearl hair clip.
<Picture 2> is the identity anchor for her body proportions, uniform, skirt, thigh strap and boots.
<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 anime-restyled edit of <Video 1>: the white mannequin is replaced by <Subject 1> taken from the two turnaround sheets, while every shot, cut, lens and dance beat of <Video 1> is preserved; she performs <Subject 2> inside the studio of <Subject 3>, drawn as 2D cel-shaded anime.

retention_analysis:
<Subject 1> (appears in every shot): fully_preserved - the same rose-red eyes, wavy pale-blonde waist-length hair with the pearl clip, the same white blazer, navy tie, gold pleated skirt, left-thigh strap and white boots in every shot.
<Picture 1> (face and hair anchor): fully_preserved - eye shape and colour, brows, fringe, hair colour and the pearl clip stay identical in every close-up.
<Picture 2> (body and costume anchor): fully_preserved - uniform cut, skirt pleats, thigh strap, boot design and body proportions stay identical.
<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 2D cel-shaded anime in the style of a character design sheet: thin clean lineart, flat pastel fills with soft two-tone shading, bright highlights along the hair strands, expressive eyes, a gentle slightly desaturated palette and a painted soft-grey studio background; the white grid paper of the reference sheets is not used.
[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 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; her long blonde waves and the gold skirt pleats swing with the motion. 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.
[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 rose-red eyes looking past the fingers. Strong wide-angle distortion, the studio behind her stretched and blurred, a faint bloom around the ceiling light; her blonde waves swing forward across her cheek.
[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, the gold skirt flaring, 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; the skirt pleats and her hair follow.
[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 pearl clip and the wavy hair silhouette read clearly.
[Shot 6] At 00:07.350, a wide full-body shot: she kicks her right leg high in front of her, arms raised, the skirt lifting a little with the kick, 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.100, 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 footsteps on the glossy floor, a light rustle of skirt 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}},
        "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": ["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),
            "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_anime",
            "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 = upload(VIDEO, video=True)
    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 (4-step turbo, no refine) + Real-ESRGAN anime upscale\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 / "20261031_KDA神之八秒_金发制服_动漫版_一采864x480.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()
