#!/usr/bin/env python3
from pathlib import Path
import base64,json,subprocess,time,urllib.request,uuid,wave
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 tts(src,out):
 text=src.read_text().strip();out.parent.mkdir(parents=True,exist_ok=True)
 for a in range(6):
  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())
   data=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();tmp=out.with_suffix('.tmp.wav');tmp.write_bytes(data)
   with wave.open(str(tmp),'rb') as w:assert w.getnframes()>0
   tmp.replace(out);return
  except Exception: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):
 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));out.write_bytes(base64.b64decode(d['data'][0]['b64_json']))
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 cream whiteboard background, thumbnail-first mobile hierarchy. '+brief['intro']['concept']+' Exact large readable Vietnamese text only: PHÒNG ĐANG IM LẶNG and BỤNG BỖNG RÉO VÌ SAO? No other text, no watermark, 16:9.',P/'images/intro_poster.png')
image('Classic expressive stick-figure doodle on warm cream whiteboard background, relaxed person walking after a meal while a simple non-anthropomorphic intestine moves one gas bubble and liquid pocket forward. 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')
