#!/usr/bin/env python3
import json, subprocess, sys, time
from pathlib import Path

PROJECT = Path('/data/video-pipeline/Youtube-Video-Maker/Project/01062026-003-Tran-Quoc-Toan')
GEN_SCRIPT = Path('/home/hermes/.hermes/skills/media/gen-img-gpt/scripts/gen_img_gpt.py')
PLAN = PROJECT / 'script/character_reference_plan.json'
LOG = PROJECT / 'logs/step05_character_refs_run.log'
MANIFEST = PROJECT / 'logs/step05_character_refs_manifest.json'
STYLE = '16:9 horizontal landscape character reference concept sheet on warm antique parchment, 13th-century Trần dynasty Đại Việt Vietnam, sepia brown ochre charcoal ink wash, handcrafted Vietnamese co phong historical feeling, controlled face/full-body/costume details for identity locking, clean negative space, historically grounded.'
NEG = 'No modern objects, no fantasy armor, no Chinese opera costume, no Qing/Ming palace drift, no European medieval armor, no Japanese samurai look, no text labels, no watermark, no vertical portrait canvas, no square canvas.'

def log(msg):
    line = time.strftime('%Y-%m-%d %H:%M:%S ') + msg
    print(line, flush=True)
    LOG.parent.mkdir(parents=True, exist_ok=True)
    with LOG.open('a', encoding='utf-8') as f:
        f.write(line + '\n')

def main():
    LOG.write_text('', encoding='utf-8')
    plan = json.loads(PLAN.read_text(encoding='utf-8'))
    refs = plan.get('references', [])
    for ref in refs:
        if not ref.get('required', False):
            continue
        out = Path(ref['output_path'])
        out.parent.mkdir(parents=True, exist_ok=True)
        if out.exists() and out.stat().st_size > 1000:
            ref['status'] = 'exists'
            ref['bytes'] = out.stat().st_size
            log(f"SKIP {ref['character_id']} exists")
            continue
        prompt = f"{STYLE}\n\nCreate a character/location reference sheet for {ref['name']}. Role: {ref.get('prompt','')}. Keep identity, costume language, materials, posture, and atmosphere consistent for later scene generation. Historically grounded Vietnamese late Trần dynasty visual culture.\n\nNegative exclusions: {NEG}"
        log(f"GENERATE {ref['character_id']} -> {out}")
        cmd = [sys.executable, str(GEN_SCRIPT), '--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=1200)
        if p.returncode != 0:
            ref['status'] = 'failed'
            ref['error'] = (p.stderr or p.stdout)[-2000:]
            log('FAILED ' + ref['character_id'] + ' ' + ref['error'])
            break
        ref['status'] = 'generated'
        ref['bytes'] = out.stat().st_size if out.exists() else 0
        log(f"OK {ref['character_id']} bytes={ref['bytes']}")
    required = [r for r in refs if r.get('required', False)]
    required_ok = all(Path(r['output_path']).exists() and Path(r['output_path']).stat().st_size > 1000 for r in required)
    plan['status'] = 'approved_for_scene_generation' if required_ok else 'needs_retry'
    plan['validation'] = {'required_refs_exist': required_ok, 'required_count': len(required), 'total_refs': len(refs)}
    PLAN.write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding='utf-8')
    MANIFEST.write_text(json.dumps({'project_id': PROJECT.name, 'step': 5, 'status': plan['status'], 'plan_path': str(PLAN), 'refs': refs}, ensure_ascii=False, indent=2), encoding='utf-8')
    log('DONE ' + json.dumps({'status': plan['status'], 'required_refs': len(required), 'refs': len(refs)}, ensure_ascii=False))
    if plan['status'] != 'approved_for_scene_generation':
        raise SystemExit('needs_retry')

if __name__ == '__main__':
    main()
