#!/usr/bin/env bash
# Official Director rv2v at 1344×768. No Veda, no turbo LoRA.
# Each of the 4 segments is its own prompt. After it finishes, ComfyUI is
# restarted so the CUDA context is dropped. The next segment pins motion from
# the on-disk latent handoff (node id 5). 12 steps, then 20 steps.
set -euo pipefail
ROOT="/home/zyw/Downloads/dl-hub/10-视频生成流水线/20261010_LMS荷塘月色_白模复刻"
RUN="/home/zyw/Downloads/dl-hub/10-视频生成流水线/20261009_0100_H3换人_源11Veda_新角色_纯白空间/run_director_rv2v_veda.py"
PROMPT="$ROOT/prompt_角色B_源98竖屏.txt"
PY="/usr/bin/python3"
SRC98="/home/zyw/Downloads/dl-hub/抖音作品库/模来AIGC/98_模来AIGC_素胚勾勒-天青色等烟雨-而你在等什么-喜欢自取-不喜勿喷-青花瓷-国风舞蹈_2880x2160.mp4"
REFS="$ROOT/新角色B_参考图"
STATUS="$ROOT/源98官方25步_seed20261025_status.txt"
AUDIO="$SRC98"
DELIVER="/home/zyw/Pictures/Wallpapers/comfyuir任务"
SSH=(ssh -i /home/zyw/.ssh/id_ed25519_gallery -o BindInterface=enp3s0f1 -o ConnectTimeout=20 zyw@192.168.31.31)

stop_comfy() {
  "${SSH[@]}" 'bash -s' << 'EOF'
pid=""
for d in /proc/[0-9]*; do
  cmd=$(tr "\0" " " < "$d/cmdline" 2>/dev/null || true)
  case "$cmd" in
    *venv/bin/python*main.py*--port\ 8189*) pid=${d#/proc/} ;;
  esac
done
if [ -z "$pid" ]; then
  echo "comfy already down"
  exit 0
fi
echo "stop comfy pid $pid"
kill "$pid" || true
for _ in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
  kill -0 "$pid" 2>/dev/null || exit 0
  sleep 1
done
kill -9 "$pid" || true
sleep 1
kill -0 "$pid" 2>/dev/null && exit 1 || exit 0
EOF
}

wait_comfy() {
  local i code
  for i in $(seq 1 40); do
    code=$(curl -sS -o /dev/null -w "%{http_code}" --interface enp3s0f1 --noproxy '*' --max-time 5 http://192.168.31.31:8189/system_stats || true)
    if [ "$code" = "200" ]; then
      echo "comfy up"
      return 0
    fi
    sleep 5
  done
  echo "FAILED ComfyUI 没有在 200 秒内起来" | tee "$STATUS"
  exit 1
}

restart_comfy() {
  echo "RESTART comfyui" | tee -a "$STATUS"
  stop_comfy
  "${SSH[@]}" 'bash ~/restart_comfy.sh'
  wait_comfy
}

mux() {
  local dir="$1" steps="$2" src dst
  src=$(find "$dir" -name "*_seg3_*.mp4" -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-)
  if [ -z "$src" ]; then
    echo "FAILED 没有第4段成片 $dir" | tee "$STATUS"
    exit 1
  fi
  dst="$ROOT/源98官方25步_768x1344/20261013_H3源98_青花瓷_角色B_竖屏_官方${steps}步_原声.mp4"
  ffmpeg -y -i "$src" -i "$AUDIO" -map 0:v:0 -map 1:a:0 -c:v copy -c:a copy "$dst"
  echo "MUX $dst"
  ffprobe -v error -select_streams v:0 -show_entries stream=width,height,nb_frames,duration -of default=nw=1 "$dst"
}

run_pass() {
  local steps="$1" prefix="$2" out="$3" sel
  mkdir -p "$out"
  for sel in 0 1 2 3; do
    echo "RUNNING ${steps}步 段${sel}" | tee "$STATUS"
    "$PY" -u "$RUN" \
      --prompt "$PROMPT" \
      --video m98_ref_480x864_530f.mp4 \
      --image charB_face_threeview.jpg \
      --image charB_body_threeview.jpg \
      --seg-prompt "0:141:$PROMPT" \
      --seg-prompt "141:141:$PROMPT" \
      --seg-prompt "282:141:$PROMPT" \
      --seg-prompt "423:107:$PROMPT" \
      --run-selection "$sel" \
      --width 768 --height 1344 --ref-max-size 1344 \
      --steps "$steps" --cfg 1 --seed 20261025 \
      --sampler res_multistep --scheduler simple \
      --shift-video 12 --shift-audio 3 \
      --no-lora \
      --continuity --continuity-mode latent --continuity-overlap 22 --continuity-keep-tail 1 \
      --audio-mode generate \
      --filename-prefix "${prefix}_seg${sel}" \
      --outdir "$out"
    newest=$(find "$out" -name "*_seg${sel}_*.mp4" -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-)
    if [ -n "$newest" ]; then
      if /usr/bin/python3 "$ROOT/check_framing.py" "$newest" >>"$STATUS" 2>&1; then
        echo "seg${sel} 构图自检通过" | tee -a "$STATUS"
      else
        echo "FAILED seg${sel} 构图自检命中漂移（$(basename "$newest")）→ 中止，避免继续白跑" | tee -a "$STATUS"
        exit 1
      fi
    fi
    restart_comfy
  done
  mux "$out" "$steps"
  echo "DONE ${steps}步" | tee -a "$STATUS"
}

run_pass 25 video/h3_m98_charB_s25 "$ROOT/源98官方25步_768x1344"
echo "DONE 官方25步完成" | tee "$STATUS"
