#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""LMS 官方工作流跑通脚本（竖屏少女奔跑 5s）

Stage A：用 H3 官方原生节点 MiniMaxH3ReferenceToVideo(REF2VA) 生成"源片段"（LMS 是对齐二采，必须有源）
Stage B：**直接跑官方 minimax_h3_lms_workflow.json**（只改文件名/尺寸/源视频/输出名，见 patches）

用法：
  python3 run_lms.py stage_a          # 只跑 Stage A
  python3 run_lms.py stage_b          # 只跑 Stage B（需要 Stage A 产物）
  python3 run_lms.py all
"""
from __future__ import annotations

import json
import subprocess
import sys
import time
import uuid
from pathlib import Path

import requests

sys.path.insert(0, str(Path(__file__).parent))
import ui2api  # noqa: E402

COMFY = "http://192.168.31.31:8189"
WORK = Path("/home/zyw/Downloads/lms-run")
REF_DIR = WORK / "refs"
TASK_DIR = Path("/home/zyw/Downloads/dl-hub/10-视频生成流水线/20261010_0210_LMS少女奔跑竖屏")
STAGE_A_DIR = TASK_DIR / "stage_a"
LMS_DIR = TASK_DIR / "lms"

W, H, N, FPS = 576, 1024, 124, 24.0        # 竖屏 9:16 / 5.17s（17n+5 合法帧数）
SEED_A = 888888
SEED_B = 42                                 # 官方 RandomNoise 默认值

S = requests.Session()
S.trust_env = False                          # 不走代理


# ---------------- 基础 IO ----------------
def upload_image(local: str | Path, remote_name: str) -> str:
    with open(local, "rb") as f:
        r = S.post(f"{COMFY}/upload/image", files={"image": (remote_name, f, "image/jpeg")},
                   data={"type": "input", "overwrite": "true"}, timeout=120)
    r.raise_for_status()
    print(f"  上传图片 → {remote_name}")
    return remote_name


def upload_video(local: str | Path, remote_name: str) -> str:
    with open(local, "rb") as f:
        r = S.post(f"{COMFY}/upload/image", files={"image": (remote_name, f, "video/mp4")},
                   data={"type": "input", "overwrite": "true"}, timeout=900)
    r.raise_for_status()
    print(f"  上传视频 → {remote_name}")
    return remote_name


def submit_and_wait(api: dict, timeout_min: int = 90, tag: str = "") -> dict:
    payload = {"prompt": api, "client_id": f"lms-{uuid.uuid4().hex[:8]}"}
    r = S.post(f"{COMFY}/prompt", json=payload, timeout=60)
    if r.status_code != 200:
        raise RuntimeError(f"[{tag}] 提交失败 {r.status_code}: {r.text[:1500]}")
    pid = r.json()["prompt_id"]
    print(f"[{tag}] 已提交 prompt_id={pid}，等待生成…")
    t0 = time.time()
    while time.time() - t0 < timeout_min * 60:
        time.sleep(15)
        try:
            h = S.get(f"{COMFY}/history/{pid}", timeout=30).json()
        except Exception:
            continue
        if pid in h:
            st = h[pid].get("status", {})
            if st.get("completed"):
                print(f"[{tag}] 完成，用时 {time.time()-t0:.0f}s")
                return h[pid]
            if st.get("status_str") == "error":
                msgs = [m for m in st.get("messages", []) if m[0] in ("execution_error", "execution_interrupted")]
                raise RuntimeError(f"[{tag}] 执行失败: {json.dumps(msgs, ensure_ascii=False)[:1500]}")
        # 队列里是否还在
        q = S.get(f"{COMFY}/queue", timeout=30).json()
        running = [x[1] for x in q.get("queue_running", [])]
        if pid not in running and int(time.time() - t0) % 60 < 15:
            print(f"[{tag}] …仍在执行/排队中（{int(time.time()-t0)}s）")
    raise TimeoutError(f"[{tag}] 超时 >{timeout_min} 分钟")


def fetch_output_video(entry: dict, dest_dir: Path, name: str) -> Path:
    dest_dir.mkdir(parents=True, exist_ok=True)
    for nid, out in (entry.get("outputs") or {}).items():
        for key in ("gifs", "videos", "video", "images"):  # 原生 SaveVideo 把视频报在 images 下
            for v in out.get(key, []) or []:
                if isinstance(v, dict) and str(v.get("filename", "")).endswith((".mp4", ".webm", ".mov")):
                    r = S.get(f"{COMFY}/view", params={"filename": v["filename"],
                                                       "subfolder": v.get("subfolder", ""),
                                                       "type": v.get("type", "output")}, timeout=900, stream=True)
                    r.raise_for_status()
                    p = dest_dir / name
                    with open(p, "wb") as f:
                        for chunk in r.iter_content(1 << 20):
                            f.write(chunk)
                    print(f"  下载 → {p} ({p.stat().st_size/1e6:.2f} MB)")
                    return p
    raise RuntimeError(f"未找到输出视频: {json.dumps(entry.get('outputs'), ensure_ascii=False)[:800]}")


# ---------------- Stage A：源片段（官方原生 REF2VA 节点） ----------------
PROMPT_A = """subject_definitions:
<Subject 1> is the young East Asian woman who appears in every shot of the target video. Her face, eyebrows, eyes, nose, mouth, skin and hairstyle come from <Picture 1>, a head-and-shoulders turnaround sheet of the SAME person seen from front, side and back: long straight black hair parted in the middle, long side-swept bangs framing the face, hair falling well past the shoulders, fair even skin, calm dark eyes, soft pink lips. Her body proportions, limbs, posture and her clothing come from <Picture 2>, a full-body turnaround sheet of that SAME woman seen from front, side and back: slim build, long legs, wearing a white short-sleeve crew-neck T-shirt with a black collar band and black sleeve trim and a small cartoon graphic on the chest, black fitted short shorts with two metallic buttons on the left hip, white knee-high socks and white low-top sneakers with tan soles. The three views inside each sheet are one identical person and never several people.
summary:
[reference generation] The target video is a 5-second vertical 9:16 live-action clip of <Subject 1> sprinting on an outdoor school running track in late-afternoon sunlight, using <Picture 1> for her face and hair and <Picture 2> for her body, limbs and outfit.
retention_analysis:
<Subject 1> (appears in [Shot 1] and [Shot 2]): fully_preserved - the face, hair and skin follow <Picture 1>; the body proportions, limbs, white top with black trim, black shorts, white knee-high socks and white sneakers follow <Picture 2>; both turnaround sheets are appearance references only and are never rendered as extra people.
detailed_description:
Realistic live-action photography, warm late-afternoon sunlight, natural skin texture, a shallow depth of field that turns the background into long horizontal streaks, and steady handheld tracking that bounces slightly with the runner's steps.
[Shot 1] A vertical medium-full shot tracks alongside the young woman from her left as she sprints down the outer lane of a red rubber running track. <Subject 1> is the only person in the frame: her face, long black hair and pale skin match <Picture 1>, and her white short-sleeve top with black collar and sleeve trim, black fitted shorts, white knee-high socks and white sneakers match <Picture 2>. She faces the camera in three-quarter view, arms pumping close to her body with bent elbows and loosely closed fists, long hair lifting and streaming behind her. Her front foot lands on the ball of the foot and the white sock compresses at the ankle; the tan soles of her sneakers flash into view as she pushes off each stride. Small beads of sweat shine on her temples and the hem of her T-shirt flutters upward with every step. Behind her, blurred green trees and a chain-link fence sweep past from right to left, with warm sunlight flaring along the top edge of the vertical frame. The camera moves at her running speed and keeps her centred and steady.
[Shot 2] At 00:02.900 the shot cuts to a low front tracking angle: the camera sits close to the track surface and retreats backwards as she runs straight toward the lens. Her face and long hair fill the upper half of the vertical frame while her arms cross in front of her chest, and the white knee-high socks and sneakers grow larger in the lower half as she closes the distance. The red track and blurring white lane lines rush beneath her feet. Her expression stays focused and slightly breathless, mouth just open, and she holds the sprint to the end of the clip as the camera keeps retreating and the warm light stays on her face.
overall_soundscape:
Dry rubber-soled sneakers striking the track surface in a fast even rhythm, quick rhythmic breathing close to the microphone, the rustle of cotton fabric and swinging hair, light wind hissing past, and distant birdsong from the trees; outdoor ambience stays continuous across both shots.
non_diegetic_music:
N/A
"""


def stage_a_prompt(head: str, body: str) -> dict:
    return {
        "1": {"class_type": "UNETLoader", "inputs": {
            "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors", "weight_dtype": "default"}},
        "2": {"class_type": "MiniMaxH3SigmaShift", "inputs": {
            "model": ["1", 0], "shift_video": 12.0, "shift_audio": 3.0}},
        "58": {"class_type": "ModelAttentionBackend", "inputs": {
            "model": ["2", 0], "attention": "comfy kitchen attention"}},
        "59": {"class_type": "MiniMaxLowVRAMAttention", "inputs": {"model": ["58", 0], "head_chunks": 4}},
        "60": {"class_type": "MiniMaxChunkFeedForward", "inputs": {
            "model": ["59", 0], "chunks": 4, "seq_threshold": 4352}},
        "64": {"class_type": "LoraLoaderModelOnly", "inputs": {
            "model": ["60", 0], "lora_name": "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors",
            "strength_model": 1.0}},
        "10": {"class_type": "CLIPLoader", "inputs": {
            "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors", "type": "minimax", "device": "default"}},
        "11": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_video_vae_fp16.safetensors"}},
        "12": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_audio_vae_fp32.safetensors"}},
        "20": {"class_type": "LoadImage", "inputs": {"image": head}},
        "21": {"class_type": "LoadImage", "inputs": {"image": body}},
        "30": {"class_type": "MiniMaxH3ReferenceToVideo", "inputs": {
            "clip": ["10", 0], "vae": ["11", 0], "audio_vae": ["12", 0], "prompt": PROMPT_A,
            "width": W, "height": H, "length": N, "ref_image_size": "match",
            "ref_images.ref_image_0": ["20", 0], "ref_images.ref_image_1": ["21", 0]}},
        "40": {"class_type": "RandomNoise", "inputs": {"noise_seed": SEED_A}},
        "41": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "euler"}},
        "42": {"class_type": "BasicScheduler", "inputs": {
            "model": ["64", 0], "scheduler": "simple", "steps": 8, "denoise": 1.0}},
        "43": {"class_type": "CFGGuider", "inputs": {
            "model": ["64", 0], "positive": ["30", 0], "negative": ["30", 0], "cfg": 1.0}},
        "44": {"class_type": "SamplerCustomAdvanced", "inputs": {
            "noise": ["40", 0], "guider": ["43", 0], "sampler": ["41", 0], "sigmas": ["42", 0],
            "latent_image": ["30", 1]}},
        "50": {"class_type": "LTXVSeparateAVLatent", "inputs": {"av_latent": ["44", 0]}},
        "51": {"class_type": "VAEDecode", "inputs": {"samples": ["50", 0], "vae": ["11", 0]}},
        "52": {"class_type": "VAEDecodeAudio", "inputs": {"samples": ["50", 1], "vae": ["12", 0]}},
        "53": {"class_type": "CreateVideo", "inputs": {"images": ["51", 0], "fps": FPS, "audio": ["52", 0]}},
        "54": {"class_type": "SaveVideo", "inputs": {
            "video": ["53", 0], "filename_prefix": "lms/stage_a_run_girl", "format": "mp4", "codec": "h264"}},
    }


def run_stage_a() -> Path:
    TASK_DIR.mkdir(parents=True, exist_ok=True)
    print("=== Stage A：生成源片段（官方原生 MiniMaxH3ReferenceToVideo）===")
    head = upload_image(REF_DIR / "head-turnaround.jpg", "lms_head_turnaround.jpg")
    body = upload_image(REF_DIR / "body-turnaround.jpg", "lms_body_turnaround.jpg")
    api = stage_a_prompt(head, body)
    (STAGE_A_DIR).mkdir(parents=True, exist_ok=True)
    (STAGE_A_DIR / "api_prompt.json").write_text(json.dumps({"prompt": api}, ensure_ascii=False, indent=1), encoding="utf-8")
    (STAGE_A_DIR / "prompt.txt").write_text(PROMPT_A, encoding="utf-8")
    entry = submit_and_wait(api, timeout_min=60, tag="stageA")
    out = fetch_output_video(entry, STAGE_A_DIR, "stageA_source_run_girl_576x1024_124f.mp4")
    return out


# ---------------- Stage B：官方 LMS 工作流 ----------------
def run_stage_b(src_video: Path, keep_comparison: bool = False) -> Path:
    LMS_DIR.mkdir(parents=True, exist_ok=True)
    print("=== Stage B：官方 LMS 工作流（minimax_h3_lms_workflow.json）===")
    remote = upload_video(src_video, "lms_src_run_girl_576x1024_124f.mp4")

    wf = json.load(open("/tmp/lms_workflow.json", encoding="utf-8"))
    patches = {
        3: {"vae_name": "minimax_h3_video_vae_fp16.safetensors"},
        4: {"aspect_ratio": "9:16 (Portrait Widescreen)", "megapixels": 0.59, "multiple": 32},
        5: {"value": 5.0},                       # 时长 5s → ComfyMathExpression 算出 124 帧
        42: {"lora_name": "h3/minimax_h3_lms_v1.0_r64.safetensors"},
        320: {"video": remote},
        47: {"filename_prefix": "lms/lms_run_girl_576x1024_124f"},
    }
    keep = [47] if not keep_comparison else None
    api, report = ui2api.convert(wf, COMFY, keep_outputs=keep, patches=patches)
    api["13"]["inputs"]["noise_seed"] = SEED_B
    (LMS_DIR / "api_prompt.json").write_text(json.dumps({"prompt": api}, ensure_ascii=False, indent=1), encoding="utf-8")
    (LMS_DIR / "convert_report.txt").write_text("\n".join(report), encoding="utf-8")
    print("\n".join(report))
    entry = submit_and_wait(api, timeout_min=90, tag="stageB-LMS")
    out = fetch_output_video(entry, LMS_DIR, "lms_run_girl_576x1024_124f_raw.mp4")
    return out


def mux_source_audio(lms_video: Path, src_video: Path) -> Path:
    """官方 LMS 图里音频轨是 EmptyAudio(静音)，官方 ChainLMSGuide 口径是"保留源片段音轨"→回接。"""
    final = lms_video.with_name(lms_video.stem.replace("_raw", "") + "_with_audio.mp4")
    cmd = ["ffmpeg", "-y", "-i", str(lms_video), "-i", str(src_video),
           "-map", "0:v:0", "-map", "1:a:0?", "-c:v", "copy", "-c:a", "aac", "-shortest", str(final)]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0 or not final.exists():
        print("  ffmpeg 回接音轨失败：", r.stderr[-800:])
        return lms_video
    print(f"  已回接源音轨 → {final}")
    return final


if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else "all"
    if mode in ("stage_a", "all"):
        p = run_stage_a()
        (WORK / "stage_a_path.txt").write_text(str(p), encoding="utf-8")
    if mode in ("stage_b", "all"):
        src = Path((WORK / "stage_a_path.txt").read_text().strip())
        raw = run_stage_b(src)
        mux_source_audio(raw, src)
