#!/usr/bin/env bash
set -u
cd /data/video-pipeline/Youtube-Video-Maker/Project/01062026-003-Tran-Quoc-Toan
MAX_ATTEMPTS=${MAX_ATTEMPTS:-12}
SLEEP_SECONDS=${SLEEP_SECONDS:-180}
WORKERS=${STEP06_WORKERS:-1}
for attempt in $(seq 1 "$MAX_ATTEMPTS"); do
  echo "$(date '+%F %T') attempt ${attempt}/${MAX_ATTEMPTS} STEP06_WORKERS=${WORKERS}"
  STEP06_WORKERS="$WORKERS" python3 scripts_run_step_06_images.py
  code=$?
  python3 - <<'PY'
from pathlib import Path
import json
P=Path('/data/video-pipeline/Youtube-Video-Maker/Project/01062026-003-Tran-Quoc-Toan')
scenes=json.loads((P/'script/scenes.json').read_text())['scenes']
missing=[s['scene_id'] for s in scenes if not (P/'images/scenes'/f"{s['scene_id']}.png").exists()]
print({'existing':len(scenes)-len(missing),'missing_count':len(missing),'missing':missing[:10]+(['...'] if len(missing)>10 else [])})
PY
  python3 - <<'PY' && exit 0
from pathlib import Path
import json, sys
P=Path('/data/video-pipeline/Youtube-Video-Maker/Project/01062026-003-Tran-Quoc-Toan')
scenes=json.loads((P/'script/scenes.json').read_text())['scenes']
missing=[s for s in scenes if not (P/'images/scenes'/f"{s['scene_id']}.png").exists()]
thumbs=list((P/'images/thumbnails').glob('*.png')) if (P/'images/thumbnails').exists() else []
sys.exit(0 if not missing and thumbs else 1)
PY
  if [ "$attempt" -lt "$MAX_ATTEMPTS" ]; then
    echo "$(date '+%F %T') sleeping ${SLEEP_SECONDS}s before next retry"
    sleep "$SLEEP_SECONDS"
  fi
done
exit 1
