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

PROJECT = Path('/data/video-pipeline/Youtube-Video-Maker/Project/28052026-002-Tran-Quang-Dieu-Bui-Thi-Xuan')
GEN_SCRIPT = Path('/home/hermes/.hermes/skills/media/gen-img-gpt/scripts/gen_img_gpt.py')
PLAN = PROJECT / 'script/character_reference_plan.json'
BIBLE = PROJECT / 'script/character_bible.json'
LOG = PROJECT / 'logs/step05_character_refs_run.log'
MANIFEST = PROJECT / 'logs/step05_character_refs_manifest.json'

BASE_NEG = 'No modern objects, no fantasy armor, no Chinese opera costume, no European medieval armor, no Japanese samurai look, no text labels, no watermark, no vertical portrait canvas, no square canvas, no multiple unrelated characters.'
STYLE = '16:9 horizontal landscape character reference concept sheet on warm antique parchment, Vietnamese late 18th century Tay Son era, sepia brown ochre charcoal ink wash, handcrafted co phong Vietnamese historical feeling, multiple small controlled views/details allowed for identity locking, clean negative space, historically grounded.'

PROMPTS = {
  'tran_quang_dieu': "Create a character reference sheet for Tran Quang Dieu, a mature Vietnamese Tay Son grand general from late 18th century Binh Dinh. Dignified calm face, focused eyes, lean strong military build, restrained moustache, dark indigo-brown battle robe, lacquered leather or lamellar armor, cloth sash, sword at waist, composed commander posture. Include face close-up, full body, armor/costume details, and one small command pose. Historically grounded Vietnamese, not fantasy.",
  'bui_thi_xuan': "Create a character reference sheet for Bui Thi Xuan, a Vietnamese female Tay Son general and elephant corps commander from late 18th century Binh Dinh. Strong martial bearing, sharp focused eyes, hair tied for battle, athletic posture, resolute expression, dark crimson-brown indigo martial robe, fitted armor vest, waist sash, sword or spear, subtle war elephant motif/detail. Heroic and tragic, dignified, not sexualized.",
  'quang_trung': "Create a character reference sheet for Nguyen Hue / Quang Trung, Vietnamese Tay Son emperor-warrior in his 30s-40s. Intense commanding gaze, compact powerful build, imperial military robe with muted gold and brown accents, battlefield cloak, sword, Tay Son banners, Vietnamese historical emperor-warrior, grounded not fantasy.",
  'nguyen_anh': "Create a character reference sheet for Nguyen Anh / Gia Long, Vietnamese Nguyen restoration leader in late 18th century. Stern composed noble-military face, calculating gaze, formal posture, dark formal military robe, southern Nguyen army context, naval/fortress hints, historically grounded opposing leader, not caricature."
}

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():
    plan = json.loads(PLAN.read_text(encoding='utf-8'))
    LOG.write_text('', encoding='utf-8')
    for ref in plan['references']:
        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'
            log(f"SKIP {ref['character_id']} exists {out}")
            continue
        prompt = f"{STYLE}\n\n{PROMPTS[ref['character_id']]}\n\nNegative exclusions: {BASE_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=900)
        if p.returncode != 0:
            ref['status'] = 'failed'
            ref['error'] = (p.stderr or p.stdout)[-2000:]
            log(f"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 plan['references'] if r['priority']=='required']
    plan['validation']['required_refs_exist'] = all(Path(r['output_path']).exists() for r in required)
    plan['status'] = 'generated_pending_user_approval' if plan['validation']['required_refs_exist'] else 'in_progress'
    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':plan['references']}, ensure_ascii=False, indent=2), encoding='utf-8')
    log('DONE '+json.dumps({'status':plan['status'], 'refs':len(plan['references'])}, ensure_ascii=False))

if __name__ == '__main__':
    main()
