import os,sys,json,hashlib,subprocess
from pathlib import Path

def load_env(path):
 for line in Path(path).read_text(errors='ignore').splitlines():
  line=line.strip()
  if line and not line.startswith('#') and '=' in line:
   k,v=line.split('=',1);os.environ.setdefault(k.strip(),v.strip().strip('"\''))
load_env('/opt/OpenMontage/.env')
sys.path.insert(0,'/opt/OpenMontage')
from tools.graphics.cx_image import CXImage
P='gacmai_20260718_091744';R=Path('/data/video-pipeline/GacMaiAudio/project')/P;O=R/'assets/images';A=R/'artifacts';O.mkdir(parents=True,exist_ok=True)
base='One coherent premium cinematic semi-realistic HAND-PAINTED illustrated Vietnamese audio-drama film-poster campaign, dark teal and near-black foundation, cream and pale-gold editorial serif typography, restrained amber highlights, dramatic key and rim lighting, layered theatrical depth, visible elegant brushwork. Clearly illustration, never photography, never plastic 3D, never flat vector, never UI cards or buttons. Typography must be integrated directly into the commissioned poster artwork by the image provider, fully readable and correctly spelled. '
prompts={
'intro_typography_rev1.png':('1920x1080',base+'NATIVE LANDSCAPE 16:9 KEY ART. Nguyễn Hoài Lan, Vietnamese woman age 42, low-tied black hair, blue-gray rolled-sleeve shirt, charcoal trousers, worn ivory canvas shoes, waits beside a scratched dark-teal table-tennis table holding a blank ticket and old wooden paddle. Modest community recreation hall, abstract booking board and tick-only clock, restrained tension and dignity, no accusation. EXACTLY THREE readable text strings and NO OTHER glyphs anywhere: large title “Bàn Số Bốn”; brand “Gác Mái Audio”; legal line “Truyện độc quyền, nghiêm cấm sao chép dưới mọi hình thức”. Preserve exact Vietnamese diacritics, capitalization, spaces and punctuation. No pseudo-text, no numerals, no labels, no watermark.'),
'left_typography_rev1.png':('1080x1920',base+'NATIVE TRUE PORTRAIT 9:16 FULL-BLEED LEFT RAIL, authored vertically. NO PEOPLE, NO FACES, NO SILHOUETTES. Atmospheric empty table-tennis hall motifs only: worn table edge, net, blank ticket shape, clock hands without numerals, amber beam and painterly particles. EXACTLY FOUR free-standing readable typography strings integrated in negative space and NO OTHER glyphs: “Gác Mái Audio”, “Like”, “Share”, “Subscribe”. Preserve exact case and spelling. Typography must not appear inside plaques, cards, buttons, signboards, borders or UI elements. No pseudo-text, no labels, no watermark.'),
'right_typography_rev1.png':('1080x1920',base+'NATIVE TRUE PORTRAIT 9:16 FULL-BLEED ENSEMBLE POSTER, authored vertically. EXACTLY SIX identifiable Vietnamese adults, 3 women and 3 men, all faces complete. Protagonist Nguyễn Hoài Lan age 42 is clearly dominant in foreground, low-tied black hair, blue-gray rolled-sleeve shirt, holding blank ticket and worn wooden table-tennis paddle. Supporting adults: Lê Thu Hạnh woman 35 by abstract magnetic board; Vũ Minh Thư woman 29 ready with paddle; Trần Minh Quang man 38 holding blank punched cream paid-slot card; Phạm Quốc Dũng man 51 looking at a tick-only wall clock; Đỗ Văn Phúc man 56 observing separately with calm decision-maker bearing. Preserve authority separation, dignity, no villain. EXACTLY ONE readable text string and NO OTHER glyphs: large title “Bàn Số Bốn”. Preserve exact Vietnamese diacritics and capitalization. No character names, no numerals, no pseudo-text, no labels, no watermark. All six faces and title fully visible and safe after tiny symmetric edge trim.')}
provider=CXImage();results=[]
for name,(size,prompt) in prompts.items():
 path=O/name
 r=provider.execute({'prompt':prompt,'model':'cx/gpt-5.5-image','size':size,'quality':'high','background':'auto','image_detail':'high','output_format':'png','n':1,'output_path':str(path)})
 if not r.success:raise RuntimeError(f'{name}: {r.error}')
 if not path.exists():raise RuntimeError(f'missing {path}')
 probe=subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=width,height','-of','json',str(path)],text=True)
 stream=json.loads(probe)['streams'][0];w=int(stream['width']);h=int(stream['height'])
 results.append({'file':str(path),'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'requested_size':size,'measured_width':w,'measured_height':h,'measured_aspect':w/h,'provider':'cx','model':'cx/gpt-5.5-image'})
rec={'status':'generated_pending_exact_text_cast_style_qa','revision':'typography_rev1','results':results};(A/'visual_typography_generation_rev1.json').write_text(json.dumps(rec,ensure_ascii=False,indent=2)+'\n');print(json.dumps(rec,ensure_ascii=False))
