#!/usr/bin/env bash
# 高中國文/英文/數學:等各章講稿(chNN.narration.json)寫好且驗證通過,就用安琪老師 + 曉臻合成該章影片。
# 用法:tools/queue-hs-videos.sh <科目 chinese|english|math>...   已完成的影片會跳過;最多等約 6 小時。
cd "$(dirname "$0")/.."
for round in $(seq 1 360); do
  pending=0
  for s in "$@"; do for t in g1-1 g1-2 g2-1 g2-2 g3-1 g3-2; do for n in 01 02 03 04 05 06; do
    dir=database/seeders/courses/high-school-$s/$t; out=public/videos/hs-$s-$t-ch$n.mp4
    [ -s "$out" ] && continue
    pending=1
    mkdir "/tmp/hs-lock-$s-$t-$n" 2>/dev/null || continue   # 別的佇列正在做這一章
    if [ -s $dir/ch$n.narration.json ] && node tools/validate-narration.mjs $dir/ch$n.php $dir/ch$n.narration.json --allow-english 2>&1 | tail -1 | grep -q '^OK'; then
      log=/tmp/mkv-hs-$s-$t-ch$n.log
      if node tools/make-video2.mjs $dir/ch$n.php $out --narration=$dir/ch$n.narration.json --strict-narration --avatar=public/images/teacher-angel.jpg --avatar-legs=0.88-0.95 --avatar-cache=storage/app/avatar-angel > $log 2>&1; then echo "OK   $out"; else echo "FAIL $out: $(grep -m1 -E 'Error|錯誤|找不到' $log | cut -c1-150)"; fi
    fi
    rmdir "/tmp/hs-lock-$s-$t-$n" 2>/dev/null
  done; done; done
  [ $pending -eq 0 ] && break
  sleep 60
done
echo "高中影片佇列結束 $(date +%H:%M)"
