#!/usr/bin/env python3
import subprocess, sys, json, os
from pathlib import Path
from datetime import datetime
PROJECT=Path('/data/video-pipeline/Youtube-Video-Maker/Project/31052026-001-Nguyen-Hue-Quang-Trung')
GEN=Path('/home/hermes/.hermes/skills/media/gen-img-gpt/scripts/gen_img_gpt.py')
LOG=PROJECT/'logs/step06_thumbnails_run.log'; MAN=PROJECT/'logs/step06_thumbnails_manifest.json'
def log(m):
    line=f"[{datetime.now().isoformat(timespec='seconds')}] {m}"; print(line,flush=True); LOG.parent.mkdir(parents=True,exist_ok=True); LOG.open('a',encoding='utf-8').write(line+'\n')
def run(name,out,prompt):
    if out.exists() and out.stat().st_size>1000: return {'name':name,'status':'skipped_existing','path':str(out),'bytes':out.stat().st_size}
    cmd=[sys.executable,str(GEN),'--prompt',prompt,'--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=480)
    if p.returncode: return {'name':name,'status':'failed','error':(p.stderr or p.stdout)[-2000:]}
    return {'name':name,'status':'generated','path':str(out),'bytes':out.stat().st_size if out.exists() else 0}
base='''cinematic Vietnamese historical biography poster about Nguyễn Huệ / Quang Trung and the spring 1789 victory over Qing armies. Large heroic portrait of Quang Trung on the left or center-left, fierce bright eyes, Vietnamese Tây Sơn emperor-general armor and robe language, smoky battlefield of Ngọc Hồi Đống Đa and Thăng Long behind him, Qing troops collapsing in the distance, dramatic manuscript/parchment texture, dark sepia bronze black palette, metallic-gold Vietnamese brush lettering title over irregular black ink-splash/grunge title panel. Title text: QUANG TRUNG ĐẠI PHÁ QUÂN THANH. High contrast, readable YouTube historical thumbnail, not scene ink-wash window, not airy negative-space page, not modern objects, no watermark, no logo.'''
prompts=[('thumb_16x9_final',PROJECT/'output/thumbnails/thumb_16x9_final.png',base+' 16:9 horizontal 1920x1080 composition.'),('thumb_9x16_final',PROJECT/'output/thumbnails/thumb_9x16_final.png',base+' TikTok-safe vertical poster composition around 1080x1280, keep face and title in central safe area, not full 1080x1920 crop.')]
res=[]
for n,o,p in prompts:
    log('Generating '+n); r=run(n,o,p); res.append(r); log(f"{n} {r['status']}")
    if r['status']=='failed': break
status='completed' if all(r['status'] in ('generated','skipped_existing') for r in res) and len(res)==2 else 'failed'
MAN.write_text(json.dumps({'status':status,'results':res},ensure_ascii=False,indent=2),encoding='utf-8')
raise SystemExit(0 if status=='completed' else 1)
