#!/usr/bin/env python3
from pathlib import Path
import base64,json,struct,sys,time,urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
P=Path(__file__).resolve().parents[1];assert P.name=='041-Vi-Sao-Mieng-Ban-Kho-Khi-Cang-Thang'
ENV=Path('/home/hermes/.hermes/skills/image-generation/gen-img-gpt/references/.env');URL='http://192.168.40.11:20128/v1/images/generations'
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('missing image key')
def valid(path):
 try:
  d=path.read_bytes();w,h=struct.unpack('>II',d[16:24]);return len(d)>10000 and d[:8]==b'\x89PNG\r\n\x1a\n' and d[12:16]==b'IHDR' and w>=1024 and h>=576 and d[-8:-4]==b'IEND'
 except:return False
def one(item,k):
 out=Path(item['output_path']).resolve();assert P in out.parents;out.parent.mkdir(parents=True,exist_ok=True)
 if valid(out):return item['id'],'existing'
 for attempt in range(5):
  tmp=out.with_suffix('.tmp.png')
  try:
   body={'model':'cx/gpt-5.5-image','prompt':item['prompt'],'size':'1536x1024','response_format':'b64_json'}
   req=urllib.request.Request(URL,data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+k,'Content-Type':'application/json'},method='POST')
   data=json.load(urllib.request.urlopen(req,timeout=1200));tmp.write_bytes(base64.b64decode(data['data'][0]['b64_json']))
   if not valid(tmp):raise RuntimeError('invalid image')
   tmp.replace(out);return item['id'],'ok'
  except Exception as e:
   tmp.unlink(missing_ok=True)
   if attempt==4:return item['id'],f'fail:{type(e).__name__}'
   time.sleep(10*(attempt+1))
def main():
 m=json.loads((P/'prompts/image_prompts.json').read_text());by={x['id']:x for x in m['items']};ids=[int(x) for x in sys.argv[1:]] or sorted(by);assert all(i in by for i in ids)
 k=key(); res=[]
 with ThreadPoolExecutor(max_workers=min(8,len(ids))) as pool:
  fut={pool.submit(one,by[i],k):i for i in ids}
  for f in as_completed(fut):
   r=f.result();res.append(r);print(r[0],r[1],flush=True)
 res.sort();bad=[x for x in res if x[1].startswith('fail')];print('ARTIFACT_GATE',len(res)-len(bad),bad);raise SystemExit(bool(bad))
if __name__=='__main__':main()
