import base64, json, struct, time, urllib.request, zlib
from pathlib import Path

# A generated 64x64 solid red PNG; no user image is read or uploaded.
def chunk(kind, data):
    return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
raw = b''.join(b'\0' + b'\xff\0\0' * 64 for _ in range(64))
png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB',64,64,8,2,0,0,0)) + chunk(b'IDAT',zlib.compress(raw)) + chunk(b'IEND',b'')
body = {'model':'ornith-sglang','temperature':0,'max_tokens':128,
        'chat_template_kwargs':{'enable_thinking':False},
        'messages':[{'role':'user','content':[
            {'type':'text','text':'What is the dominant color of this image? Answer with one color word only.'},
            {'type':'image_url','image_url':{'url':'data:image/png;base64,'+base64.b64encode(png).decode()}}
        ]}]}
started=time.monotonic()
try:
    req=urllib.request.Request('http://127.0.0.1:8130/v1/chat/completions',data=json.dumps(body).encode(),headers={'Content-Type':'application/json'})
    with urllib.request.urlopen(req,timeout=300) as r:
        response=json.load(r)
    content=response['choices'][0]['message']['content']
    result={'pass':content.strip().lower().rstrip('.')=='red','content':content,'usage':response.get('usage'),'seconds':time.monotonic()-started,'image':'synthetic red64x64; local API only'}
except Exception as e:
    result={'pass':False,'error':str(e),'seconds':time.monotonic()-started}
print(json.dumps(result,indent=2))
Path('/home/lab/bench/ornith/modular/sglang/results/vision-smoke.json').write_text(json.dumps(result,indent=2))
raise SystemExit(0 if result['pass'] else 1)
