#!/usr/bin/env bash
# 國中部(數學、國文…):改由「琪琪老師」出鏡,聲音沿用曉臻(語音快取可沿用,所以省資源)。
# 用法:tools/queue-jh-qiqi.sh [科目 math|chinese ...]   做過的(標記檔 ~/mkvideo/qiqi-done)會跳過;先寫暫存檔,成功才覆蓋 public/videos。
# 有講稿(chNN.narration.json)就逐句對齊(需驗證通過);沒有講稿的章節沿用「自動朗讀簡報文字」。
cd "$(dirname "$0")/.."
export SHOT_PAR=${SHOT_PAR:-2}
subjects=("$@"); [ ${#subjects[@]} -eq 0 ] && subjects=(math chinese)
mkdir -p ~/mkvideo/qiqi-done
for s in "${subjects[@]}"; do for t in g7-1 g7-2 g8-1 g8-2 g9-1 g9-2; do for n in 01 02 03 04 05 06; do
  dir=database/seeders/courses/junior-high-$s/$t; out=public/videos/jh-$s-$t-ch$n.mp4; mark=~/mkvideo/qiqi-done/jh-$s-$t-ch$n
  [ -e "$mark" ] && continue
  [ -s $dir/ch$n.php ] || continue
  # (已移除「只換已有影片」限制:國中數學缺的章節也一併做)
  nar=(); if [ -s $dir/ch$n.narration.json ]; then
    node tools/validate-narration.mjs $dir/ch$n.php $dir/ch$n.narration.json --allow-english 2>&1 | tail -1 | grep -q '^OK' || continue
    nar=(--narration=$dir/ch$n.narration.json --strict-narration)
  fi
  tmp=$HOME/mkvideo/qq-$s-$t-$n.mp4; log=/tmp/mkv-qq-$s-$t-ch$n.log
  if nice -n 10 node tools/make-video2.mjs $dir/ch$n.php $tmp "${nar[@]}" \
       --avatar=public/images/teacher-qiqi-sheet.jpg --avatar-grid=4x2:6,2,4,1,3,7,8,5 --avatar-height=340 --cycle=1,3,0,4,2,5 --avatar-cache=storage/app/avatar-qiqi > $log 2>&1 && [ -s "$tmp" ]; then
    mv "$tmp" "$out" && { [ -s "${tmp%.mp4}-b.mp4" ] && mv "${tmp%.mp4}-b.mp4" "${out%.mp4}-b.mp4"; true; } && touch "$mark" && echo "OK   $out"
  else echo "FAIL $out: $(grep -m1 -E 'Error|錯誤|找不到' $log | cut -c1-150)"; fi
done; done; done
echo "琪琪老師國中影片完成 $(date +%H:%M)"
