"""Runs ON gex44. usage: site_probe.py <url_root> <out>: progress, lookup, browse at 1280 and 375 px; opens a tile
(3D viewer) and searches; reports page errors, horizontal overflow, broken images."""
import asyncio, 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(root, out):
    res = {'errors': [], 'pages': {}}
    async with async_playwright() as p:
        b = await p.chromium.launch(args=GPU)
        for w, h in ((1280, 860), (375, 780)):
            pg = await b.new_page(viewport={'width': w, 'height': h})
            pg.on('pageerror', lambda e: res['errors'].append(str(e)[:300]))
            pg.on('console', lambda m: m.type == 'error' and res['errors'].append(m.text[:300]))
            for name in ('index.html', 'lookup.html', 'browse/index.html'):
                await pg.goto(root + name); await pg.wait_for_load_state('networkidle'); await pg.wait_for_timeout(800)
                info = await pg.evaluate("""({ov: document.documentElement.scrollWidth - innerWidth,
                    broken: [...document.images].filter(i => i.complete && i.naturalWidth === 0 && i.getBoundingClientRect().top < 3000).length})""")
                res['pages'][f'{name}@{w}'] = info
                await pg.screenshot(path=f"{out}/{name.replace('/', '_')}-{w}.jpg", type='jpeg', quality=80)
            await pg.fill('#q', 'yellow cab'); await pg.wait_for_timeout(300)
            res['pages'][f'search@{w}'] = await pg.evaluate("document.getElementById('info').innerText")
            await pg.screenshot(path=f'{out}/search-{w}.jpg', type='jpeg', quality=80)
            await pg.fill('#q', 'tank'); await pg.wait_for_timeout(200)
            res['pages'][f'gap@{w}'] = await pg.evaluate("document.getElementById('info').innerText")
            await pg.fill('#q', 'lighthouse'); await pg.wait_for_timeout(300)
            await pg.click('.tile'); await pg.wait_for_timeout(2500)
            await pg.screenshot(path=f'{out}/viewer-{w}.jpg', type='jpeg', quality=80)
            await pg.close()
        await b.close()
    print(json.dumps(res, indent=1))
asyncio.run(main(*sys.argv[1:3]))
