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

PROJECT = Path('/data/video-pipeline/Youtube-Video-Maker/Project/29052026-001-Nguyen-Phi-Y-Lan')
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'

BASE_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, no unrelated character lineup.'
STYLE = '16:9 horizontal landscape character reference concept sheet on warm antique parchment, Đại Việt Lý dynasty Vietnam, sepia brown ochre charcoal ink wash, handcrafted Vietnamese co phong historical feeling, multiple small controlled views/details allowed for identity locking, clean negative space, historically grounded.'

PROMPTS = {
  'y_lan': 'Create a character reference sheet for Ỷ Lan / Linh Nhân Hoàng thái hậu, a Vietnamese woman of Đại Việt Lý dynasty. Show consistent identity from village mulberry-picking girl beside an orchid tree to dignified Nguyên phi and later Hoàng thái hậu: calm intelligent eyes, composed face, gentle but politically strong presence, Vietnamese facial features, early Lý dynasty clothing. Include face close-up, village full-body, royal full-body, hand/costume details. Elegant, complex, compassionate yet decisive, not fantasy, not sexualized.',
  'ly_thanh_tong': 'Create a character reference sheet for King Lý Thánh Tông of Đại Việt, 11th century Vietnamese Lý dynasty ruler. Mature composed king, observant wise gaze, dignified posture, early Lý royal robes, restrained gold and deep red-brown, Thăng Long court feeling. Include face close-up, full-body royal pose, robe/crown details, small court scene cue. Historically grounded Đại Việt, not Chinese emperor cosplay, not fantasy.',
  'ly_nhan_tong': 'Create a character reference sheet for Lý Nhân Tông / prince Càn Đức, young Vietnamese king of Đại Việt Lý dynasty. Child-to-young ruler identity, solemn protected expression, royal youth attire, court attendants implied, vulnerable but destined for authority. Include child prince view, young king view, face close-up, costume details. Historically grounded Vietnamese Lý dynasty.',
  'ly_thuong_kiet': 'Create a character reference sheet for Lý Thường Kiệt, mature Vietnamese commander and statesman of the Lý dynasty. Stern strategic face, disciplined posture, grounded Đại Việt military clothing and armor, command robe, sword, Như Nguyệt river defense atmosphere. Include face close-up, full-body commander, armor/robe details, command pose. Not fantasy, not Chinese general drift.',
  'thuong_duong_hoang_hau': 'Create a character reference sheet for Thượng Dương Hoàng hậu, dignified Vietnamese queen of Đại Việt Lý dynasty linked to palace tragedy. Adult royal woman, restrained sorrowful expression, formal queenly Lý robes, palace interior cues, tragic and vulnerable but not villainous. Include face close-up, full-body queen pose, robe details, subdued court lighting. Historically grounded Vietnamese.'
}

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()
