"""Runs ON gex44 (GPU). usage: compare_probe.py <site_url> <out_dir> <spec.json>
spec = {row: {id, kit, scale}, files: [original, candidate, ...]} (paths relative to the site). Loads compare.html,
calls window.__compare and writes <out>/result.json ({file, worst, sides: [{pct, model, changed}]}) + <out>/<i>_<side>.jpg."""
import asyncio, base64, json, sys
from playwright.async_api import async_playwright
GPU = ['--no-sandbox', '--use-angle=gl-egl', '--use-gl=angle', '--ignore-gpu-blocklist', '--enable-gpu']


async def main(url, out, spec):
    spec = json.load(open(spec)); errs = []
    async with async_playwright() as p:
        b = await p.chromium.launch(args=GPU)
        pg = await b.new_page(viewport={'width': 512, 'height': 512})
        pg.on('pageerror', lambda e: errs.append(str(e)[:300]))
        await pg.goto(url + 'compare.html')
        await pg.wait_for_function('window.__ready === true', timeout=60000)
        r = await pg.evaluate('([row, files]) => window.__compare(row, files)', [spec['row'], spec['files']])
        await b.close()
    if not r.get('ok'):
        json.dump({'ok': False, 'error': r.get('error'), 'page_errors': errs}, open(f'{out}/result.json', 'w'), indent=1)
        print('compare failed:', r.get('error'), errs); sys.exit(2)
    for i, res in enumerate(r['results']):
        for k, s in enumerate(res['sides']):
            open(f'{out}/{i}_{k}.jpg', 'wb').write(base64.b64decode(s.pop('jpg').split(',', 1)[1]))
    json.dump({'ok': True, 'results': r['results'], 'page_errors': errs}, open(f'{out}/result.json', 'w'), indent=1)
    print('compared', len(r['results']) - 1, 'candidates;', 'page errors', len(errs))


asyncio.run(main(*sys.argv[1:4]))
