#!/usr/bin/env python3
"""Headless reproduce: screenshot the puzzle board, dump geometry for pixel checks."""
import sys, json
from playwright.sync_api import sync_playwright

PORT = 8123
N = int(sys.argv[1]) if len(sys.argv) > 1 else 3
TAG = sys.argv[2] if len(sys.argv) > 2 else "before"

with sync_playwright() as pw:
    b = pw.chromium.connect_over_cdp("http://localhost:9222")
    ctx = b.new_context(viewport={"width": 390, "height": 844}, device_scale_factor=int(sys.argv[3]) if len(sys.argv)>3 else 3,
                        
                        user_agent="Mozilla/5.0 (Linux; Android 13) Chrome/120")
    # 外网字体在 VM 网络里会挂起：一律拦截，本地回退字体渲染
    def _rt(r):
        r.continue_() if "localhost" in r.request.url else r.abort()
    ctx.route("http://**", _rt); ctx.route("https://**", _rt)
    page = ctx.new_page()
    page.on("console", lambda m: m.type == "error" and print("CONSOLE-ERR:", m.text))
    page.goto(f"http://localhost:{PORT}/index.html", wait_until="domcontentloaded", timeout=20000)
    page.wait_for_timeout(500)
    page.click(f'#diff button[data-n="{N}"]')
    page.click("#go-gallery")
    page.wait_for_timeout(300)
    page.click("#gal-grid-cards .spec")
    page.wait_for_function("()=>{const g=document.getElementById('ghost');return g&&g.width>0&&!document.getElementById('board-loading').classList.contains('show');}", timeout=15000)
    page.wait_for_timeout(700)  # settle (tray pad sync etc.)
    geo = page.evaluate("""()=>{
      const w=document.getElementById('board-wrap'), g=document.getElementById('ghost');
      const R=e=>{const r=e.getBoundingClientRect();return {x:r.x,y:r.y,w:r.width,h:r.height};};
      return {wrap:R(w), ghost:R(g),
              ghostPx:[g.width,g.height],
              ghostCss:[g.style.width,g.style.height],
              wrapCss:[w.style.width,w.style.height]};}""")
    print(json.dumps(geo))
    page.screenshot(path=f"/home/user/shots/{TAG}_n{N}.png")
    b2 = geo["wrap"]
    page.screenshot(path=f"/home/user/shots/{TAG}_n{N}_board.png",
                    clip={"x": b2["x"]-30, "y": b2["y"]-30, "width": b2["w"]+60, "height": b2["h"]+60})
    ctx.close()
print("done", TAG, N)
