#!/usr/bin/env python3
"""Turn on "Show framing" and screenshot it, plus print the building model's walls and a count of framing members.

Usage:  python tools/framing_check.py houses/<slug>/index.html [--views sw,se] [--cam "x,y,z:tx,ty,tz" --name close] [--cut 1]
"""
import argparse, asyncio, pathlib, json
from playwright.async_api import async_playwright
ARGS=['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--ignore-gpu-blocklist']
async def main(a):
    html=pathlib.Path(a.html).resolve(); out=html.parent/'renders'; out.mkdir(exist_ok=True)
    async with async_playwright() as p:
        b=await p.chromium.launch(args=ARGS); pg=await b.new_page(viewport={'width':1400,'height':860})
        errs=[]; pg.on('pageerror',lambda e: errs.append(str(e))); pg.on('console',lambda m: m.type=='error' and errs.append(m.text))
        await pg.goto(html.as_uri()); await pg.wait_for_function('window.__viewer',timeout=30000); await pg.wait_for_timeout(2000)
        M=await pg.evaluate('__viewer.model()')
        print('model:', {k:len(v) for k,v in M.items() if isinstance(v,list)})
        if a.walls: print(*[f"  {w['id']:<28} {w['kind']:<6} L{w['lvl']} {w['u1']-w['u0']:6.2f}'  openings {len(w['openings'])}" for w in M['walls']], sep='\n')
        await pg.evaluate('__viewer.setFraming(true)'); await pg.wait_for_timeout(2500)
        if a.cut is not None: await pg.evaluate(f'__viewer.setCut({a.cut})'); await pg.wait_for_timeout(500)
        counts=await pg.evaluate('__viewer.framingCounts()'); print('members:', sum(counts.values())); print(json.dumps(counts,indent=1))
        if a.cam:
            pos,tgt=(list(map(float,s.split(','))) for s in a.cam.split(':'))
            await pg.evaluate(f"__viewer.goView('sw'); __viewer.setCamera({pos},{tgt})"); await pg.wait_for_timeout(2000)
            f=out/f'framing_{a.name or "cam"}.png'; await pg.screenshot(path=str(f)); print(f)
        for v in filter(None,(a.views or '').split(',')):
            await pg.evaluate(f"__viewer.goView('{v}')"); await pg.wait_for_timeout(2200)
            if a.cut is not None: await pg.evaluate(f'__viewer.setCut({a.cut})'); await pg.wait_for_timeout(500)
            f=out/f'framing_{v}{"_cut"+str(a.cut) if a.cut is not None else ""}.png'; await pg.screenshot(path=str(f)); print(f)
        if errs: print('PAGE ERRORS:',*errs,sep='\n  ')
        await b.close()
ap=argparse.ArgumentParser(); ap.add_argument('html'); ap.add_argument('--views'); ap.add_argument('--cam'); ap.add_argument('--name'); ap.add_argument('--cut',type=int); ap.add_argument('--walls',action='store_true')
asyncio.run(main(ap.parse_args()))
