#!/usr/bin/env python3
import json
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path

PROJECT=Path('/data/video-pipeline/Youtube-Video-Maker/Project/31052026-001-Nguyen-Hue-Quang-Trung')
GEN_SCRIPT=Path('/home/hermes/.hermes/skills/media/gen-img-gpt/scripts/gen_img_gpt.py')
LOG=PROJECT/'logs/step06_first50_images_run.log'
MAN=PROJECT/'logs/step06_first50_minimal_retry_manifest.json'

def log(msg):
    line=f"[{datetime.now().isoformat(timespec='seconds')}] {msg}"
    print(line, flush=True)
    with LOG.open('a',encoding='utf-8') as f: f.write(line+'\n')

def prompt(s):
    n=s.get('narration') or s.get('text','')
    if s.get('type')=='heading':
        return f"Vietnamese old-calligraphy chapter title card, 16:9 horizontal, warm antique paper, subtle ink wash, small seal stamp accent, airy breathing room. Exact title: {n}. No modern typography, no logo, no watermark."
    return f"Vietnamese historical ink-wash storytelling illustration, 16:9 horizontal canvas, centered irregular ink-wash window on warm antique cream paper, painted content only 65-70 percent of page with 30-35 percent antique paper negative space. Late 18th-century Dai Viet, Tay Son era, historically grounded Vietnamese clothing, terrain, villages, courts, armies, river geography. One cinematic narrative scene matching this narration beat: {n}. Clear focal action, environment, emotional staging. Not character sheet, not multiple views, not modern, not logo, not watermark, not text, not edge-to-edge, not glossy 3D."

def gen(s):
    sid=s['scene_id']; out=PROJECT/'images/scenes'/f'{sid}.png'
    if out.exists() and out.stat().st_size>1000: return {'scene_id':sid,'status':'exists'}
    cmd=[sys.executable,str(GEN_SCRIPT),'--prompt',prompt(s),'--output',str(out),'--size','auto','--quality','auto','--background','auto','--image-detail','high','--output-format','png','--n','1']
    p=subprocess.run(cmd,text=True,capture_output=True,timeout=360)
    if p.returncode!=0: return {'scene_id':sid,'status':'failed','error':(p.stderr or p.stdout)[-1000:]}
    return {'scene_id':sid,'status':'generated','bytes':out.stat().st_size if out.exists() else 0}

scenes=json.loads((PROJECT/'script/scenes.json').read_text(encoding='utf-8'))['scenes'][:50]
results=[]
while True:
    missing=[s for s in scenes if not (PROJECT/'images/scenes'/f"{s['scene_id']}.png").exists()]
    if not missing: break
    s=missing[0]
    log('Minimal retry '+s['scene_id'])
    r=gen(s); results.append(r); log(f"Minimal {r['scene_id']} {r['status']}")
    if r['status']=='failed':
        # continue to next attempt only if transient terminated; otherwise stop after recording
        if 'terminated' not in r.get('error','').lower(): break
        continue
out={'status':'completed_limited_50_pending_review' if not [s for s in scenes if not (PROJECT/'images/scenes'/f"{s['scene_id']}.png").exists()] else 'incomplete','results':results,'remaining_missing':[s['scene_id'] for s in scenes if not (PROJECT/'images/scenes'/f"{s['scene_id']}.png").exists()]}
MAN.write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(out,ensure_ascii=False,indent=2))
raise SystemExit(0 if out['status'].startswith('completed') else 1)
