#!/usr/bin/env python3
"""Stage B: official LMS workflow, one pass per 17n+5 segment. No Veda.

The official graph is /tmp/lms_workflow.json (UI format). ui2api keeps SaveVideo #47.
Caption stays the official enhance sentence. Turbo LoRA stays in front of LMS.
"""
from __future__ import annotations

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

import requests

sys.path.insert(0, "/home/zyw/Downloads/lms-run")
import ui2api  # noqa: E402

COMFY = "http://192.168.31.31:8189"
TASK = Path("/home/zyw/Downloads/dl-hub/10-视频生成流水线/20261010_LMS荷塘月色_白模复刻")
WF = Path("/tmp/lms_workflow.json")
SSH = [
    "ssh", "-i", "/home/zyw/.ssh/id_ed25519_gallery",
    "-o", "BindInterface=enp3s0f1", "-o", "ConnectTimeout=15",
    "zyw@192.168.31.31",
]
ENHANCE = (
    "Enhance this video with sharp, crisp details while preserving a natural photorealistic appearance."
)
# H3 横屏原生是 1344×768。864×480 按原比例放大、再对齐到 32，落到 1376×768
# （scale 1.5926）。720p 的 1280×720 不合法：720 不能被 32 整除。
MP = 1.0518756
OUT_W, OUT_H = 1376, 768
WIN = 107
SEED = 42

S = requests.Session()
S.trust_env = False


def sh(cmd: list[str], timeout: int = 120) -> str:
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    if r.returncode != 0:
        raise RuntimeError(f"{cmd[0]} failed: {r.stderr[-800:]}")
    return r.stdout


def sh_bytes(cmd: list[str], timeout: int = 180) -> bytes:
    r = subprocess.run(cmd, capture_output=True, timeout=timeout)
    if r.returncode != 0:
        raise RuntimeError(f"{cmd[0]} failed: {r.stderr.decode('utf-8', 'replace')[-800:]}")
    return r.stdout


def probe_frames(path: Path) -> tuple[int, int, int]:
    out = sh([
        "ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=width,height,nb_frames,r_frame_rate",
        "-of", "json", str(path),
    ])
    st = json.loads(out)["streams"][0]
    w, h = int(st["width"]), int(st["height"])
    n = int(st.get("nb_frames") or 0)
    if n <= 0:
        n = int(sh(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0",
                    "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", str(path)]).strip())
    return w, h, n


def split_plan(n: int) -> list[tuple[int, int]]:
    """107-frame windows at 1376×768 (17*6+5, 4.46s). Step 102 leaves a
    5-frame overlap and covers 515 frames in 5 windows. 124 frames does not
    tile this clip with a constant short overlap.
    """
    length = WIN
    step = WIN - 5
    if n < length:
        raise SystemExit(f"成片只有 {n} 帧，短于一个原生窗口")
    starts = list(range(0, n - length, step))
    if not starts or starts[-1] != n - length:
        starts.append(n - length)
    return [(s, length) for s in starts]


def extract(src: Path, start: int, length: int, dest: Path) -> None:
    dest.parent.mkdir(parents=True, exist_ok=True)
    sh([
        "ffmpeg", "-y", "-i", str(src),
        "-vf", f"trim=start_frame={start}:end_frame={start + length},setpts=PTS-STARTPTS",
        "-an", "-frames:v", str(length), "-c:v", "libx264", "-pix_fmt", "yuv420p",
        str(dest),
    ], timeout=180)
    w, h, n = probe_frames(dest)
    if (w, h, n) != (864, 480, length):
        raise RuntimeError(f"{dest.name} 变成了 {w}x{h} {n}f，期望 864x480 {length}f")


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


def log_offset() -> int:
    return int(sh(SSH + ["stat -c %s /home/zyw/comfyui_8189.log"]).strip())


def wait_remote(prefix: str, offset: int, timeout_min: int = 90) -> str:
    """Wait until ComfyUI writes prefix*.mp4 and the log says Prompt executed. No /queue."""
    deadline = time.time() + timeout_min * 60
    glob = f"/home/zyw/ComfyUI/output/{prefix}*.mp4"
    while time.time() < deadline:
        try:
            raw = sh(SSH + [f"""python3 - << 'PY'
import glob, os
off = {offset}
with open('/home/zyw/comfyui_8189.log','rb') as f:
    f.seek(off)
    text = f.read().decode('utf-8','replace')
flags = [k for k in ('OutOfMemoryError','CUDA out of memory','execution_error','NVRM: Xid','fallen off the bus','unspecified launch failure','AcceleratorError') if k in text]
files = sorted(glob.glob({glob!r}), key=os.path.getmtime)
newest = files[-1] if files else ''
size = os.path.getsize(newest) if newest else 0
print('FLAGS', ','.join(flags))
print('EXECUTED', int('Prompt executed in' in text))
print('FILE', newest)
print('SIZE', size)
PY"""], timeout=40)
        except RuntimeError as exc:
            err = str(exc)
            if any(s in err for s in ("timed out", "Connection refused", "Connection reset", "No route to host")):
                print(f"ssh 暂时连不上，继续等: {err[-180:]}", flush=True)
                time.sleep(20)
                continue
            raise
        flags = executed = file = size = ""
        for line in raw.splitlines():
            if line.startswith("FLAGS "):
                flags = line[6:]
            elif line.startswith("EXECUTED "):
                executed = line.split()[1]
            elif line.startswith("FILE "):
                file = line[5:]
            elif line.startswith("SIZE "):
                size = line.split()[1]
        if flags:
            raise RuntimeError(f"LMS 失败 {prefix}: {flags}\n{raw}")
        if executed == "1" and file and int(size or 0) > 100000:
            return file
        time.sleep(20)
    raise TimeoutError(f"LMS 超时 {prefix}")


def build_api(remote_video: str, prefix: str) -> dict:
    wf = json.loads(WF.read_text(encoding="utf-8"))
    patches = {
        3: {"vae_name": "minimax_h3_video_vae_fp16.safetensors"},
        # 官方图默认 1:1 / 0.5MP。ImageResize 会把 864×480 装进 736 的方框，得到 736×408，
        # AIToolkit 再放大回 864×480。16:9 / 0.4MP / 32 的计算结果就是 864×480，参考帧不再缩放。
        4: {"aspect_ratio": "16:9 (Widescreen)", "megapixels": 0.4, "multiple": 32},
        30: {"target_megapixels": MP, "max_length": 0},
        42: {"lora_name": "h3/minimax_h3_lms_v1.0_r64.safetensors"},
        320: {"video": remote_video},
        47: {"filename_prefix": prefix},
    }
    api, report = ui2api.convert(wf, COMFY, keep_outputs=[47], patches=patches)
    (TASK / "lms_convert_report.txt").write_text("\n".join(report), encoding="utf-8")
    types = {n["class_type"] for n in api.values()}
    if "VedaSparseAttention" in types:
        raise RuntimeError("LMS 图里出现了 Veda，已中止")
    if api.get("13", {}).get("class_type") != "RandomNoise":
        raise RuntimeError(f"节点 13 不是 RandomNoise: {api.get('13')}")
    api["13"]["inputs"]["noise_seed"] = SEED
    # 官方增强句在 PrimitiveStringMultiline，再连到 CLIPTextEncode。
    got = None
    for n in api.values():
        if n["class_type"] != "CLIPTextEncode":
            continue
        text = n["inputs"].get("text")
        if isinstance(text, list):
            src = api[str(text[0])]["inputs"]
            got = next((src[k] for k in ("value", "string", "text") if k in src), None)
        else:
            got = text
    if got != ENHANCE:
        raise RuntimeError(f"增强句被改动: {got!r}")
    loras = [
        (n["inputs"].get("lora_name"), n["inputs"].get("strength_model"))
        for n in api.values()
        if n["class_type"] == "LoraLoaderModelOnly"
    ]
    if ("h3/minimax_h3_lms_v1.0_r64.safetensors", 1.0) not in [(a, b) for a, b in loras]:
        raise RuntimeError(f"LMS LoRA 不在图里: {loras}")
    return api


def submit(api: dict) -> str:
    r = S.post(f"{COMFY}/prompt", json={"prompt": api, "client_id": f"lms107-{uuid.uuid4().hex[:8]}"}, timeout=60)
    if r.status_code != 200:
        raise RuntimeError(f"提交失败 {r.status_code}: {r.text[:1500]}")
    return r.json()["prompt_id"]


def download(remote: str, dest: Path) -> None:
    rel = remote.split("/output/", 1)[1]
    sh(["scp", "-i", "/home/zyw/.ssh/id_ed25519_gallery", "-o", "BindInterface=enp3s0f1",
        f"zyw@192.168.31.31:{remote}", str(dest)], timeout=300)
    print(f"  下载 {rel} -> {dest}")


def queue_idle() -> None:
    r = S.get(f"{COMFY}/queue", timeout=20)
    r.raise_for_status()
    d = r.json()
    running = len(d.get("queue_running") or [])
    pending = len(d.get("queue_pending") or [])
    if running or pending:
        raise RuntimeError(f"队列不是空的 running={running} pending={pending}，不插队")


def assemble(outs: list[Path], starts: list[int], total: int, dest: Path) -> None:
    """Blend a 5-frame ramp across each native window. Two clips in memory at a time."""
    import numpy as np

    length = WIN
    w, h = OUT_W, OUT_H

    def load(path: Path) -> np.ndarray:
        raw = sh_bytes([
            "ffmpeg", "-v", "error", "-i", str(path),
            "-f", "rawvideo", "-pix_fmt", "rgb24", "-",
        ], timeout=300)
        arr = np.frombuffer(raw, np.uint8)
        expect = length * h * w * 3
        if arr.size != expect:
            raise RuntimeError(f"{path.name} 字节数 {arr.size} 对不上 {w}x{h}x{length}")
        return arr.reshape(length, h, w, 3)

    proc = subprocess.Popen(
        [
            "ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", "24",
            "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "16", str(dest),
        ],
        stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
    )
    assert proc.stdin is not None
    prev = load(outs[0])
    prev_start = starts[0]
    written = 0
    try:
        for i in range(1, len(outs)):
            nxt = load(outs[i])
            nxt_start = starts[i]
            for t in range(written, nxt_start):
                proc.stdin.write(prev[t - prev_start].tobytes())
            overlap = (prev_start + length) - nxt_start
            if overlap < 1:
                raise RuntimeError(f"窗口 {i} 和上一段没有重叠")
            for k in range(overlap):
                alpha = k / (overlap - 1) if overlap > 1 else 1.0
                fa = prev[nxt_start + k - prev_start].astype(np.float32)
                fb = nxt[k].astype(np.float32)
                frame = (fa * (1 - alpha) + fb * alpha).round().clip(0, 255).astype(np.uint8)
                proc.stdin.write(frame.tobytes())
            written = nxt_start + overlap
            prev, prev_start = nxt, nxt_start
        for t in range(written, prev_start + length):
            proc.stdin.write(prev[t - prev_start].tobytes())
        if prev_start + length != total:
            raise RuntimeError(f"拼接长度 {prev_start + length} 对不上 {total}")
    finally:
        proc.stdin.close()
    err = proc.stderr.read().decode("utf-8", "replace") if proc.stderr else ""
    if proc.wait() != 0:
        raise RuntimeError(f"拼接编码失败: {err[-800:]}")


def main() -> int:
    status = TASK / "lms_status.txt"
    status.write_text("RUNNING\n", encoding="utf-8")
    try:
        src = Path(sys.argv[1])
        w, h, n = probe_frames(src)
        print(f"stage A: {w}x{h} {n}f", flush=True)
        if (w, h) != (864, 480):
            raise SystemExit(f"分辨率不是 864x480: {w}x{h}")
        parts = split_plan(n)
        seg_dir = TASK / "lms_segs"
        outs: list[Path] = []
        for i, (start, length) in enumerate(parts):
            local_out = seg_dir / f"lms_native_seg{i}.mp4"
            if local_out.exists():
                ow, oh, on = probe_frames(local_out)
                if (ow, oh, on) == (OUT_W, OUT_H, length):
                    print(f"seg{i} 已有 {ow}x{oh} {on}f，跳过", flush=True)
                    outs.append(local_out)
                    continue
            queue_idle()
            clip = seg_dir / f"seg{i}_{start}_{length}.mp4"
            extract(src, start, length, clip)
            remote_name = f"m107_native_seg{i}_{length}f.mp4"
            upload_video(clip, remote_name)
            prefix = f"lms/h3_m107_native_seg{i}"
            api = build_api(remote_name, prefix)
            (TASK / f"lms_api_seg{i}.json").write_text(json.dumps(api, ensure_ascii=False), encoding="utf-8")
            off = log_offset()
            pid = submit(api)
            print(f"seg{i} start={start} {length}f prompt_id={pid}", flush=True)
            remote_out = wait_remote(prefix, off)
            download(remote_out, local_out)
            ow, oh, on = probe_frames(local_out)
            if (ow, oh, on) != (OUT_W, OUT_H, length):
                raise RuntimeError(f"LMS seg{i} 输出 {ow}x{oh} {on}f，期望 {OUT_W}x{OUT_H} {length}f")
            outs.append(local_out)
        silent = TASK / "stageB_native_silent.mp4"
        assemble(outs, [s for s, _ in parts], n, silent)
        final = TASK / "stageB_native_原声.mp4"
        audio = TASK / "m107_audio_20.04s.m4a"
        # 成片 21.46s，原声 20.04s。不截画面，歌曲结束处自然停。
        sh([
            "ffmpeg", "-y", "-i", str(silent), "-i", str(audio),
            "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", str(final),
        ], timeout=180)
        fw, fh, fn = probe_frames(final)
        print(f"FINAL {final} {fw}x{fh} {fn}f", flush=True)
        status.write_text(f"DONE {final} {fw}x{fh} {fn}f\n", encoding="utf-8")
        return 0
    except Exception as exc:
        status.write_text(f"FAILED {exc}\n", encoding="utf-8")
        print(f"FAILED {exc}", flush=True)
        raise


if __name__ == "__main__":
    raise SystemExit(main())
