#!/usr/bin/env bash
# =============================================================================
#  餐厅戏（星罗妮妮子方法）· 角色A（红发女）× 餐厅 POV × 竖屏 9:16
#  turbo 4 步 + 二采 + latent 续接（overlap 22 / keep-tail 1）
#  照搬 20261010_LMS荷塘月色_白模复刻/run_src26ruins_portrait_turbo4.sh 那套流程，
#  **唯一差别：不传参考视频**（本场戏是纯参考图 Ref2VA，没有白模源片）。
#  三张参考图：<Picture 1> 全身三视图 / <Picture 2> 面部正+侧 / <Picture 3> 场景底板
# =============================================================================
set -euo pipefail

ROOT="/home/zyw/Downloads/dl-hub/10-视频生成流水线/20261012_H3餐厅戏_星罗妮妮子方法"
RUN="$ROOT/run_director_r2v_seg.py"   # 由 rv2v_veda 派生：task_type=r2v + timelineMode=gen_blank（无源片）
REFS="$ROOT/refs"
BODY="charA_body_threeview.jpg"
FACE="charA_face_front_side.jpg"
SCENE="scene_restaurant_counter.png"
HANDS="pov_hands_counter.png"   # <Picture 4> POV 双手锚点
P1="$ROOT/prompt_seg1_进门走近.txt"
P2="$ROOT/prompt_seg2_搭手敲台面.txt"
P3="$ROOT/prompt_seg3_台词与收尾.txt"
OUT="$ROOT/out"
PY="/usr/bin/python3"
STATUS="$ROOT/餐厅戏_status.txt"
LOG="$ROOT/餐厅戏_run.log"
SEED=20261012

# 段窗口：124 帧 = 5.17s（H3 合法段长 17k+5）
SEG0="0:124"; SEG1="124:124"; SEG2="248:124"

SSH=(ssh -i /home/zyw/.ssh/id_ed25519_gallery -o BindInterface=enp3s0f1 -o ConnectTimeout=20 zyw@192.168.31.31)
log() { echo "$(date '+%F %T') $*" | tee -a "$STATUS"; }

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 $(seq 1 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)
    [ "$code" = "200" ] && { echo "comfy up"; return 0; }
    sleep 5
  done
  log "FAILED ComfyUI 没起来"; exit 1
}
restart_comfy() { log "RESTART comfyui"; stop_comfy; "${SSH[@]}" 'bash ~/restart_comfy.sh'; wait_comfy; }
up() { curl -sS --interface enp3s0f1 --noproxy '*' --max-time 900 \
        -F "image=@$1;type=$2" -F "type=input" -F "overwrite=true" \
        http://192.168.31.31:8189/upload/image >/dev/null; }

mkdir -p "$OUT"; : > "$LOG"
log "START 餐厅戏（角色A + 餐厅POV）turbo4+二采+latent续接  无参考视频  段 124/124/124 = 372 帧 → 9:16 768x1344"
up "$REFS/$BODY"  "image/jpeg"
up "$REFS/$FACE"  "image/jpeg"
up "$REFS/$SCENE" "image/png"
up "$REFS/$HANDS" "image/png"
"${SSH[@]}" "ls -l /home/zyw/ComfyUI/input/$BODY /home/zyw/ComfyUI/input/$FACE /home/zyw/ComfyUI/input/$SCENE" | sed 's/^/  /'

for sel in 0 1 2; do
  log "RUNNING 餐厅戏 turbo4 段${sel}（单轮：一采→自动转 MP4；随即二采）"
  "$PY" -u "$RUN" \
    --prompt "$P1" --video "" \
    --image "$BODY" --image "$FACE" --image "$SCENE" --image "$HANDS" \
    --seg-prompt "$SEG0:$P1" --seg-prompt "$SEG1:$P2" --seg-prompt "$SEG2:$P3" \
    --run-selection "$sel" \
    --width 480 --height 864 --ref-max-size 864 \
    --steps 4 --cfg 1.0 --seed $SEED \
    --sampler res_multistep --scheduler simple --shift-video 12 --shift-audio 3 \
    --refine --refine-mode upscale --refine-aspect "9:16 (竖屏)" \
    --refine-upscale-method h3_latent --refine-sampler euler --refine-passes 1 \
    --refine-mp 0.984375 --refine-width 768 --refine-height 1344 \
    --refine-scheduler beta --refine-steps 3 --refine-denoise 0.2 \
    --continuity --continuity-mode latent --continuity-overlap 22 --continuity-keep-tail 1 \
    --audio-mode generate \
    --filename-prefix "video/h3_restaurant_charA_t4_seg${sel}" \
    --outdir "$OUT" 2>&1 | tee -a "$LOG"
  restart_comfy
done

SRC=$(find "$OUT" -name "*_seg2_*.mp4" -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-)
[ -n "$SRC" ] || { log "FAILED 没有最终成片"; exit 1; }
cp -f "$SRC" "$OUT/20261012_H3餐厅戏_角色A_竖屏_turbo4二采_768x1344_原片.mp4"
ffprobe -v error -select_streams v:0 -show_entries stream=width,height,nb_frames,duration -of csv=p=0 "$SRC" | tee -a "$STATUS"
log "DONE 餐厅戏（跑批）；成片待跑后加工"
