#!/usr/bin/env bash
# =============================================================================
#  新角色A（红发·战术马甲·红黑格裙）白模复刻 —— turbo 4 步 + 二采（2026-10-11）
#
#  与荷塘月色既有那趟的差别只有两处（其余全同：同一白模源 m107、同一时间线
#  0:124 / 124:124 / 248:124 / 372:107、同一 seed 20261022、同一 latent 续接
#  overlap22/keep-tail1、同一最终 1344×768、同一"每段跑完重启 ComfyUI"机制）：
#    ① 参考图换成新角色A 的两张三视图（头 / 全身）
#    ② 提示词换成 prompt_角色A_stageA.txt（已过官方 profile 校验）
#  采样档与 A/B 实验的 B 组一致：一采 864×480 4 步 turbo + 二采 1344×768 3 步。
# =============================================================================
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_角色A_stageA.txt"
REFS="$ROOT/新角色A_参考图"
FACE="charA_face_threeview.jpg"      # <Picture 1>＝头/脸三视图（身份）
BODY="charA_body_threeview.jpg"      # <Picture 2>＝全身三视图（身体＋服装）
AUDIO="$ROOT/m107_audio_20.04s.m4a"
VIDEO="m107_ref_864x480_481f.mp4"
PY="/usr/bin/python3"
OUT="$ROOT/新角色A_turbo4二采_768"
STATUS="$ROOT/新角色A_status.txt"
LOG="$ROOT/新角色A_run.log"
DELIVER="/home/zyw/Pictures/Wallpapers/comfyuir任务"

SEG0="0:124"; SEG1="124:124"; SEG2="248:124"; SEG3="372:107"

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 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)
    [ "$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
}

upload_refs() {
  log "上传参考图 → ComfyUI/input"
  curl -sS --interface enp3s0f1 --noproxy '*' --max-time 300 \
    -F "image=@$REFS/$FACE;type=image/jpeg" -F "type=input" -F "overwrite=true" \
    http://192.168.31.31:8189/upload/image >/dev/null
  curl -sS --interface enp3s0f1 --noproxy '*' --max-time 300 \
    -F "image=@$REFS/$BODY;type=image/jpeg" -F "type=input" -F "overwrite=true" \
    http://192.168.31.31:8189/upload/image >/dev/null
  "${SSH[@]}" "ls -l /home/zyw/ComfyUI/input/$FACE /home/zyw/ComfyUI/input/$BODY /home/zyw/ComfyUI/input/$VIDEO" \
    | sed 's/^/  /'
}

mkdir -p "$OUT"
: > "$LOG"
log "START 新角色A turbo4+二采  提示词=$(basename "$PROMPT")  refs=$FACE / $BODY"

# 把两张参考图传到远端 input/，并顺带确认源片在
upload_refs

for sel in 0 1 2 3; do
  log "RUNNING 新角色A turbo4 段${sel}"
  "$PY" -u "$RUN" \
    --prompt "$PROMPT" \
    --video "$VIDEO" \
    --image "$FACE" \
    --image "$BODY" \
    --seg-prompt "$SEG0:$PROMPT" \
    --seg-prompt "$SEG1:$PROMPT" \
    --seg-prompt "$SEG2:$PROMPT" \
    --seg-prompt "$SEG3:$PROMPT" \
    --run-selection "$sel" \
    --width 864 --height 480 --ref-max-size 864 \
    --steps 4 --cfg 1.0 --seed 20261022 \
    --sampler res_multistep --scheduler simple \
    --shift-video 12 --shift-audio 3 \
    --refine --refine-mode upscale --refine-aspect "16:9 (宽屏)" \
    --refine-upscale-method h3_latent --refine-sampler euler --refine-passes 1 \
    --refine-mp 0.984375 --refine-width 1344 --refine-height 768 \
    --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_m107_charA_t4_seg${sel}" \
    --outdir "$OUT" 2>&1 | tee -a "$LOG"
  restart_comfy
done

SRC=$(find "$OUT" -name "*_seg3_*.mp4" -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-)
[ -n "$SRC" ] || { log "FAILED 没有第4段成片"; exit 1; }
DST="$OUT/20261011_H3荷塘月色白模复刻_角色A红发战术装_turbo4步二采_1344x768_原声.mp4"
ffmpeg -y -v error -i "$SRC" -i "$AUDIO" -map 0:v:0 -map 1:a:0 -c:v copy -c:a aac "$DST"
cp -f "$DST" "$DELIVER/"
log "MUX $DST"
ffprobe -v error -select_streams v:0 -show_entries stream=width,height,nb_frames,duration \
        -of default=nw=1 "$DST" | tr '\n' ' ' | tee -a "$STATUS"; echo | tee -a "$STATUS"
log "DONE 新角色A"
