"""Runs ON gex44 (GPU). usage: vehicles_probe.py <site_url> <out_dir> [slugs comma list]
Loads browse/vehicles.html; per vehicle: 3/4 view in paint 1, 3/4 in paint 4 (recolour proof), side view, spinning +
steering frame; then every family lineup in random paints with an fps sample. <out>/report.json = numbers + errors."""
import asyncio, json, os, sys
from playwright.async_api import async_playwright
GPU = ['--no-sandbox', '--use-angle=gl-egl', '--use-gl=angle', '--ignore-gpu-blocklist', '--enable-gpu']
FPS = ('new Promise(r => { let n = 0; const t0 = performance.now(); const f = () => { n++; '
       'if (performance.now() - t0 < 2000) requestAnimationFrame(f); else r(n / ((performance.now() - t0) / 1000)); }; requestAnimationFrame(f); })')


async def main(url, out, only=''):
    os.makedirs(out, exist_ok=True)
    rep = {'vehicles': {}, 'lineups': {}, 'page_errors': [], 'console': []}
    async with async_playwright() as p:
        b = await p.chromium.launch(args=GPU)
        pg = await b.new_page(viewport={'width': 1440, 'height': 860})
        pg.on('pageerror', lambda e: rep['page_errors'].append(str(e)[:300]))
        pg.on('console', lambda m: m.type in ('error', 'warning') and rep['console'].append(m.text[:300]))
        await pg.goto(url + 'vehicles.html')
        await pg.wait_for_function('window.__ready === true', timeout=180000)
        vs = await pg.evaluate('window.__list')
        want = set(filter(None, only.split(',')))
        for v in vs:
            if want and v['slug'] not in want:
                continue
            r = {}
            for name, opt in (('a', {'paint': 0}), ('b', {'paint': 3}), ('side', {'paint': 1, 'view': 'side'}),
                              ('rear', {'paint': 2, 'view': 'rear'})):
                r[name] = await pg.evaluate(f"window.__show({json.dumps(v['id'])}, {json.dumps(opt)})")
                await pg.wait_for_timeout(400)
                await pg.locator('#c').screenshot(path=f"{out}/{v['slug']}-{name}.jpg", type='jpeg', quality=88)
            await pg.evaluate(f"window.__show({json.dumps(v['id'])}, {{paint: 0}})")
            await pg.click('#spin'); await pg.click('#steer'); await pg.wait_for_timeout(900)
            await pg.locator('#c').screenshot(path=f"{out}/{v['slug']}-steer.jpg", type='jpeg', quality=88)
            await pg.click('#spin'); await pg.click('#steer')
            rep['vehicles'][v['slug']] = r
        for fam in ('cars', 'motos', 'bikes', 'buses', 'wheeled', 'tanks', 'rotor', 'jets'):
            if not any(v['family'] == fam for v in vs) or want:
                continue
            rep['lineups'][fam] = await pg.evaluate(f"window.__lineup('{fam}', 7)")
            await pg.wait_for_timeout(800)
            rep['lineups'][fam]['fps'] = round(await pg.evaluate(FPS), 1)
            await pg.locator('#c').screenshot(path=f'{out}/lineup-{fam}.jpg', type='jpeg', quality=88)
        await pg.screenshot(path=f'{out}/page.png')
        await b.close()
    json.dump(rep, open(f'{out}/report.json', 'w'), indent=1)
    print(json.dumps({'n': len(rep['vehicles']), 'page_errors': rep['page_errors'][:5], 'console': rep['console'][:8],
                      'lineups': rep['lineups']}, indent=1))

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