#!/usr/bin/env bash
set -euo pipefail
PROJECT="/data/video-pipeline/Youtube-Video-Maker/Project/01062026-001-Pham-Ngu-Lao"
cd "$PROJECT"
LOG="$PROJECT/logs/retry_scene145_then_finish.log"
exec > >(tee -a "$LOG") 2>&1

echo "$(date '+%F %T') START long retry for scene_145"
python3 - <<'PY'
import json, subprocess, sys, time
from pathlib import Path
P=Path('/data/video-pipeline/Youtube-Video-Maker/Project/01062026-001-Pham-Ngu-Lao')
GEN=Path('/home/hermes/.hermes/skills/media/gen-img-gpt/scripts/gen_img_gpt.py')
out=P/'images/scenes/scene_145.png'
sc=json.loads((P/'script/scenes.json').read_text(encoding='utf-8'))['scenes']
s=next(x for x in sc if x['scene_id']=='scene_145')
prompt='16:9 horizontal Vietnamese historical ink-wash scene on antique paper, 13th-century Dai Viet Tran dynasty. A reflective symbolic scene: a Tran-era spear resting beside an old map, distant village and river, people standing with quiet resolve. Muted sepia charcoal watercolor, centered ink-wash window with paper negative space, no text, no watermark, no modern objects. Narration: '+s['narration']
for i in range(1,25):
    if out.exists() and out.stat().st_size>1000:
        print('scene_145 already exists', out.stat().st_size, flush=True)
        raise SystemExit(0)
    print(time.strftime('%F %T'), 'attempt', i, flush=True)
    cmd=[sys.executable,str(GEN),'--prompt',prompt,'--output',str(out),'--size','auto','--quality','auto','--background','auto','--image-detail','high','--output-format','png','--n','1']
    r=subprocess.run(cmd,text=True,capture_output=True,timeout=900)
    msg=(r.stderr or r.stdout)[-1200:]
    print('return',r.returncode, msg, flush=True)
    print('exists',out.exists(),out.stat().st_size if out.exists() else 0, flush=True)
    if out.exists() and out.stat().st_size>1000:
        raise SystemExit(0)
    sleep_s=300
    if 'reset after' in msg.lower():
        sleep_s=180
    print('sleep',sleep_s,'seconds', flush=True)
    time.sleep(sleep_s)
raise SystemExit(1)
PY

echo "$(date '+%F %T') scene_145 ok; continue step06-19"
STEP06_WORKERS=1 python3 scripts_run_step_06_images.py
python3 scripts_run_step_07_tts_v2.py
python3 scripts_run_step_08_compose_tts.py
python3 scripts_run_step_09_probe_audio.py
python3 scripts_run_step_10_asr_master.py
python3 scripts_run_step_11_map_subtitles.py
python3 scripts_run_step_12_clamp_subtitles.py
python3 scripts_run_step_13_split_parts.py
python3 scripts_run_step_14_render_parts.py
python3 scripts_run_step_15_concat_parts.py
python3 scripts_run_step_16_qa_main_story.py
python3 scripts_run_step_17_create_intro_segmented.py
python3 scripts_run_step_18_final_package.py
python3 scripts_run_step_19_final_qa_info.py

echo "$(date '+%F %T') DONE final pipeline"
