#!/usr/bin/env python3
from pathlib import Path
import base64,json,time,urllib.request,uuid,wave,struct
P=Path(__file__).resolve().parents[1]
VOICE='http://192.168.40.32:7861/voice/truong-giang';ENV=Path('/home/hermes/.hermes/skills/image-generation/gen-img-gpt/references/.env');IMG='http://192.168.40.11:20128/v1/images/generations'
def wavok(x):
 try:
  with wave.open(str(x),'rb') as w:return w.getnframes()>0 and w.getframerate()>0
 except:return False
def pngok(x):
 try:
  d=x.read_bytes();return len(d)>10000 and d[:8]==b'\x89PNG\r\n\x1a\n' and d[12:16]==b'IHDR' and d[-8:-4]==b'IEND'
 except:return False
def tts(src,out):
 if wavok(out):return
 text=src.read_text().strip();out.parent.mkdir(parents=True,exist_ok=True)
 for a in range(6):
  tmp=out.with_suffix('.tmp.wav')
  try:
   b='----Hermes'+uuid.uuid4().hex;parts=[]
   for k,v in {'text':text,'style':'tu_nhien','speed':'1','denoise':'true'}.items():parts.append(f'--{b}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
   tmp.write_bytes(urllib.request.urlopen(urllib.request.Request(VOICE,data=b''.join(parts)+f'--{b}--\r\n'.encode(),headers={'Content-Type':f'multipart/form-data; boundary={b}'},method='POST'),timeout=900).read())
   if not wavok(tmp):
    raise RuntimeError('wav')
   tmp.replace(out)
   return
  except Exception:
   if tmp.exists():tmp.unlink();time.sleep(10*(a+1))
 raise RuntimeError(out)
def key():
 for line in ENV.read_text().splitlines():
  if '=' in line and line.split('=',1)[1].strip():return line.split('=',1)[1].strip().strip('"\'')
 raise RuntimeError('key')
def image(prompt,out):
 if pngok(out):return
 body={'model':'cx/gpt-5.5-image','prompt':prompt,'size':'1536x1024','response_format':'b64_json'};req=urllib.request.Request(IMG,data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+key(),'Content-Type':'application/json'},method='POST');d=json.load(urllib.request.urlopen(req,timeout=1200));tmp=out.with_suffix('.tmp.png');tmp.write_bytes(base64.b64decode(d['data'][0]['b64_json']));assert pngok(tmp);tmp.replace(out)
tts(P/'narration/intro.txt',P/'audio/intro_raw.wav');tts(P/'narration/outro.txt',P/'audio/outro.wav')
brief=json.load(open(P/'logs/poster_brief.json'))
image('Classic expressive stick-figure doodle on warm light cream whiteboard background, simple imperfect black lines, thumbnail-first mobile hierarchy. '+brief['intro']['concept']+' Exact large readable Vietnamese text only: KEM CHẠM KHẨU CÁI and TRÁN BỖNG ĐAU BUỐT? No frozen brain, no other text, no watermark, 16:9.',P/'images/intro_poster.png')
image('Classic expressive stick-figure doodle on warm light cream whiteboard background, relaxed person enjoying a small spoon of ice cream slowly, subtle path from palate to forehead without a frozen brain. Exact readable text only: Bản Năng Cổ Đại and Thanks for watching. No other text, no watermark, 16:9.',P/'images/outro_poster.png')
print('ASSET_GATE PASS')
