#!/usr/bin/env bash
# 看守：等 GPU 机 ComfyUI 队列排空 → 自动开跑「三段窗口提示词 + 续接 + 二采」→ 核对产物
# 用法：nohup bash queue_watch_and_run.sh > watch.log 2>&1 &
set -u
D="$(cd "$(dirname "$0")" && pwd)"
QURL="http://192.168.31.31:8189/queue"
PREFIX="h3_rv2v_fuchouyao_segwin"

qlen() {
  curl -s --noproxy '*' -m 8 "$QURL" 2>/dev/null \
    | python3 -c "import json,sys;d=json.load(sys.stdin);print(len(d.get('queue_running') or [])+len(d.get('queue_pending') or []))" 2>/dev/null \
    || echo 1
}

echo "[$(date '+%m-%d %H:%M')] 开始监视队列（最多等 8 小时）"
for i in $(seq 1 480); do
  n="$(qlen)"
  if [ "$n" = "0" ]; then
    echo "[$(date '+%m-%d %H:%M')] 队列已空 → 开跑"
    break
  fi
  [ $((i % 10)) -eq 0 ] && echo "[$(date '+%m-%d %H:%M')] 仍在排队/执行（队列 $n）"
  sleep 60
done

cd "$D" || exit 1
nohup python3 run_director_rv2v_seg.py \
  --prompt prompt.txt \
  --video h3_rv2v_src_full_338f.mp4 \
  --image h3_rv2v_char_grok.jpg \
  --seg-prompt 0:124:prompt_seg1.txt \
  --seg-prompt 124:124:prompt_seg2.txt \
  --seg-prompt 248:90:prompt_seg3.txt \
  --width 480 --height 864 \
  --continuity --continuity-overlap 9 --keep-vram \
  --refine --refine-width 768 --refine-height 1344 --refine-mp 1.0 \
  --seed 20260927 --filename-prefix "video/${PREFIX}" --outdir "$D" \
  > "$D/run_segwin.log" 2>&1 &
sleep 25
echo "--- 提交回执 ---"; head -4 "$D/run_segwin.log"

echo "[$(date '+%m-%d %H:%M')] 等待出片（最多 4 小时）"
for i in $(seq 1 240); do
  ls "$D/${PREFIX}"_*.mp4 >/dev/null 2>&1 && break
  grep -q "没有取到输出" "$D/run_segwin.log" 2>/dev/null && break
  sleep 60
done

echo "=== run_segwin.log 末尾 ==="; tail -8 "$D/run_segwin.log"
echo "=== 产物 ==="; ls -la "$D/${PREFIX}"_*.mp4 2>/dev/null || echo "(无)"
for f in "$D/${PREFIX}"_*.mp4; do
  [ -e "$f" ] || continue
  ffprobe -v error -select_streams v:0 -show_entries stream=width,height,r_frame_rate,nb_frames,duration -of default=nw=1 "$f"
  ffprobe -v error -select_streams a:0 -show_entries stream=codec_name,channels,duration -of default=nw=1 "$f"
done
echo "=== GPU 机日志：段完成 / 续接 / 合并 ==="
~/Downloads/ssh_exec.sh 'tail -c 120000 /home/zyw/comfyui_8189_opt.log | tr "\r" "\n" | grep -iE "segment [0-9]/3 done|continuity: pinned|re-pin|Merged|Prompt executed|Segment cache pruned|ERROR|out of memory" | tail -14' 2>&1 | tail -15
echo "[$(date '+%m-%d %H:%M')] 看守结束"
