#!/usr/bin/env python3
from pathlib import Path
import base64,json,struct,sys,time,urllib.request
P=Path(__file__).resolve().parents[1]
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:
  data=path.read_bytes()
  if len(data)<=10000 or data[:8] != b'\x89PNG\r\n\x1a\n' or data[12:16] != b'IHDR': return False
  width,height=struct.unpack('>II',data[16:24])
  return width>=1024 and height>=576 and data[-8:-4] == b'IEND'
 except Exception:return False
def one(item,k):
 out=Path(item['output_path']);out.parent.mkdir(parents=True,exist_ok=True)
 if valid(out): return item['id'],'existing'
 for attempt in range(5):
  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=out.with_suffix('.tmp.png');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:
   if attempt==4:return item['id'],f'fail:{type(e).__name__}'
   time.sleep(10*(attempt+1))
def main():
 m=json.load(open(P/'prompts/image_prompts.json'));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=[one(by[i],k) for i in ids];print('\n'.join(f'{i} {s}' for i,s in res));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()
