"""Disposable houses.html only. Catalogue, close views, sloped thresholds and kit-absent evidence."""
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):
    errors, shots = [], {}
    async with async_playwright() as p:
        b = await p.chromium.launch(args=GPU)
        pg = await b.new_page(viewport={'width': 1800, 'height': 1100})
        pg.on('pageerror', lambda e: errors.append(str(e)))
        await pg.goto(f'{root}houses.html')
        await pg.wait_for_function('window.__ready === true', timeout=180000)
        fatal = await pg.evaluate('window.__error || null')
        if fatal:
            raise RuntimeError(fatal)
        for view in ['catalogue', 'patrician', 'cottage', 'tower', 'hill', 'trades', 'irregular']:
            await pg.evaluate('(v) => window.__show(v)', view)
            await pg.wait_for_timeout(1500)
            await pg.screenshot(path=f'{out}/{view}.png')
            shots[view] = await pg.evaluate('window.__stats')
        for trade in ['barn', 'smithy', 'bakery', 'tavern', 'shop']:
            for distance in [30, 8]:
                name = f'{trade}-{distance}m'
                await pg.evaluate('([t,d]) => window.__trade(t,d)', [trade, distance])
                await pg.wait_for_timeout(1000)
                await pg.screenshot(path=f'{out}/{name}.png')
                shots[name] = await pg.evaluate('window.__stats')
        for index, angle in enumerate([-.65, 0, .65]):
            name = f'window-angle-{index+1}'
            await pg.evaluate('(a) => window.__window(a)', angle)
            await pg.wait_for_timeout(700)
            await pg.screenshot(path=f'{out}/{name}.png')
            shots[name] = await pg.evaluate('window.__stats')
        await pg.evaluate('window.__slope()')
        await pg.wait_for_timeout(700)
        await pg.screenshot(path=f'{out}/slope-back-1.5-2.5.png')
        shots['slope'] = await pg.evaluate('window.__stats')
        # A real click, not just the camera API.
        await pg.locator('button[data-view="hovel"]').click()
        await pg.wait_for_timeout(500)
        assert await pg.evaluate('window.__stats.view') == 'hovel'
        await pg.goto(f'{root}houses.html?view=patrician&noTown=1')
        await pg.wait_for_function('window.__ready === true', timeout=180000)
        shots['kit-absent'] = await pg.evaluate('window.__stats')
        assert shots['kit-absent']['greyBoxes'] > 0
        assert shots['kit-absent']['warnings'] > 0
        await pg.screenshot(path=f'{out}/kit-absent.png')
        ctx = await b.new_context(viewport={'width': 390, 'height': 844}, device_scale_factor=2)
        mp = await ctx.new_page()
        mp.on('pageerror', lambda e: errors.append('phone: ' + str(e)))
        await mp.goto(f'{root}houses.html?view=cottage')
        await mp.wait_for_function('window.__ready === true', timeout=180000)
        await mp.wait_for_timeout(1000)
        await mp.screenshot(path=f'{out}/phone-cottage.png')
        shots['phone-cottage'] = await mp.evaluate('window.__stats')
        await b.close()
    result = {'fatal': fatal, 'errors': errors, 'shots': shots}
    with open(f'{out}/stats.json', 'w') as f:
        json.dump(result, f, indent=2)
    print(json.dumps({'fatal': fatal, 'errors': errors, 'shots': {k: {x: v[x] for x in ['buildings', 'triangles', 'drawCalls', 'greyBoxes', 'errors', 'warnings']} for k, v in shots.items()}}, indent=2))

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