"""Runs ON gex44. usage: fb_probe.py <url_root> <out>: browse page with the feedback API faked: collapsed by default,
open, save a note, re-run (confirm), status badge; 1280 and 375 px; page errors."""
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']
STATE = {'assets': {'building.landmark.lighthouse/harbour-lighthouse': {'feedback': [{'t': '2026-10-07T15:20:00Z', 'text': 'too blocky, needs real stone', 'user': 'x'}]}},
         'jobs': [{'id': 'a1', 'asset': 'vehicle.sea.trawler/harbour-trawler', 'state': 'running', 'note': 'Astra is rebuilding it', 'version': None}]}
async def main(root, out):
    res = {'errors': [], 'posts': []}
    async with async_playwright() as p:
        b = await p.chromium.launch(args=GPU)
        for w in (1280, 375):
            pg = await b.new_page(viewport={'width': w, 'height': 860})
            pg.on('pageerror', lambda e: res['errors'].append(str(e)[:300]))
            pg.on('dialog', lambda d: asyncio.ensure_future(d.accept()))
            async def st(route): await route.fulfill(json=STATE)
            async def post(route):
                res['posts'].append([route.request.url.rsplit('/', 1)[1], route.request.post_data]); await route.fulfill(json={'ok': True, 'job': {'id': 'z'}})
            await pg.route('**/api/state', st); await pg.route('**/api/feedback', post); await pg.route('**/api/rerun', post)
            await pg.goto(root + 'browse/index.html'); await pg.wait_for_function('window.__ready === true'); await pg.wait_for_timeout(500)
            res[f'details@{w}'] = await pg.evaluate("[document.querySelectorAll('details.fb').length, document.querySelectorAll('details.fb[open]').length]")
            await pg.fill('#q', 'lighthouse'); await pg.wait_for_timeout(300)
            await pg.click('details.fb summary'); await pg.fill('details.fb textarea', 'more weathering on the tower')
            await pg.click('details.fb [data-a=save]'); await pg.wait_for_timeout(400)
            await pg.click('details.fb summary') if not await pg.evaluate("!!document.querySelector('details.fb[open]')") else None
            await pg.fill('details.fb textarea', 'rebuild it realistic')
            await pg.click('details.fb [data-a=rerun]'); await pg.wait_for_timeout(500)
            await pg.screenshot(path=f'{out}/fb-{w}.jpg', type='jpeg', quality=80)
            await pg.fill('#q', 'trawler'); await pg.wait_for_timeout(300)
            res[f'badge@{w}'] = await pg.evaluate("[...document.querySelectorAll('.job')].map(e => e.textContent)")
            res[f'ov@{w}'] = await pg.evaluate('document.documentElement.scrollWidth - innerWidth')
            await pg.screenshot(path=f'{out}/badge-{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]))
