#!/usr/bin/env python3
"""Close-up of a 2D plan: a screenshot of one floor with the SVG view box set to a window of the drawing.

Usage:  python tools/plan_zoom.py houses/<slug>/index.html <floor> "x y w h" <out.png>
The view box is in the plan's screen frame (feet, already turned so the front is down). The easiest way to
find one: open the plan, zoom in on the area, and read document.getElementById('plansvg').getAttribute('viewBox').
"""
import asyncio, pathlib, sys
from playwright.async_api import async_playwright
ARGS = ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist']

async def main(house, lvl, vb, out):
    async with async_playwright() as p:
        b = await p.chromium.launch(args=ARGS); pg = await b.new_page(viewport={'width':1400,'height':860})
        errors = []; pg.on('pageerror', lambda e: errors.append(str(e)))
        await pg.goto(pathlib.Path(house).resolve().as_uri())
        await pg.wait_for_function('window.__viewer', timeout=30000); await pg.wait_for_timeout(2500)
        await pg.evaluate(f"__viewer.setMode('plan'); __viewer.planLevel({lvl}); document.getElementById('panel').classList.add('collapsed'); document.getElementById('plansvg').setAttribute('viewBox','{vb}')")
        await pg.wait_for_timeout(500); await pg.screenshot(path=out); await b.close()
    print(out)
    if errors: print('PAGE ERRORS:', *errors, sep='\n  ')

if __name__ == '__main__':
    asyncio.run(main(*sys.argv[1:5]))
