import asyncio, sys, json, http.server, threading, functools, os
from playwright.async_api import async_playwright
PORT = 8766
h = functools.partial(http.server.SimpleHTTPRequestHandler, directory='page')
class Q(http.server.ThreadingHTTPServer): pass
srv = Q(('127.0.0.1', PORT), h); threading.Thread(target=srv.serve_forever, daemon=True).start()
RUN = """(name)=>{const C=window.__combo;const near=(n)=>{const p=C.POSES[n];let m=0;for(let i=0;i<6;i++)m=Math.max(m,Math.abs(C.q[i]-p[i]));return m<1e-3;};
 let n=0;const conds={arrive:()=>C.st.mode==='branch'&&Math.abs(C.st.d-(Math.PI*0.45+0.6))<1e-3,idle:()=>!C.busy};
 const c=conds[name]||(()=>near(name));
 while(!c()&&n<4000){C.step(0.04);n++;} C.render(); return n;}"""
async def main():
    async with async_playwright() as p:
        b = await p.chromium.launch(executable_path='/usr/bin/google-chrome', args=['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'])
        pg = await b.new_page(viewport={'width': 1400, 'height': 900}); logs = []
        pg.on('pageerror', lambda e: logs.append('ERR ' + str(e)))
        await pg.goto(f'http://127.0.0.1:{PORT}/index.html')
        await pg.wait_for_function('window.__combo && window.__combo.ready', timeout=90000); await pg.wait_for_timeout(1200)
        el = await pg.query_selector('#stage')
        async def shot(n): await pg.wait_for_timeout(350); await el.screenshot(path=f'shots/{n}.png')
        for g, view in (('table', 'iso'), ('shelf', 'iso'), ('dolly', 'iso'), ('stand', 'iso')):
            await pg.evaluate(f"__combo.plan('{g}')")
            n = await pg.evaluate(RUN, 'arrive'); await pg.evaluate(f"__combo.setView('{view}')")
            n2 = await pg.evaluate(RUN, g); await shot(f'seq_{g}_pick')
            if g == 'shelf':
                await pg.evaluate("(()=>{const C=__combo;const f=document.getElementById('follow');if(f&&f.checked){f.click();}C.cam.position.set(4.3,1.45,-1.55);C.ctr.target.set(3.2,1.0,-2.5);C.ctr.update();C.render();})()")
                await shot('seq_shelf_close')
                await pg.evaluate("(()=>{const f=document.getElementById('follow');if(f&&!f.checked){f.click();}})()")
            n3 = await pg.evaluate(RUN, 'idle'); await shot(f'seq_{g}_done')
            st = await pg.evaluate("document.getElementById('state').textContent+' / '+document.getElementById('sub').textContent")
            print(g, 'steps', n, n2, n3, st)
        await pg.evaluate("__combo.setView('deck')"); await shot('seq_deck_after')
        await pg.evaluate("__combo.plan('door')"); n = await pg.evaluate(RUN, 'idle'); await pg.evaluate("__combo.setView('iso')"); await shot('seq_door')
        print('door steps', n, await pg.evaluate("document.getElementById('state').textContent"))
        await pg.evaluate("__combo.st.mode='lane';__combo.st.s=0.40-0.585;__combo.place(0,true);__combo.setView('side')"); await shot('seq_bump_front')
        print('\n'.join(logs) or 'ページの誤りなし')
        await b.close()
asyncio.run(main())
