#!/usr/bin/env python3
"""Render every Vanta surface to design/render/out per device profile.

Profiles mirror design/render/devices.js:
  s10          412x870 dp @3x  (Galaxy S10+, 1440x3040)
  flip5-main   360x880 dp @3x  (Galaxy Z Flip 5 main panel, 1080x2640)
  flip5-cover  360x374 dp @2x  (Galaxy Z Flip 5 cover panel, 720x748)

Usage: render.py [--device NAME] [surface ...]
With --device flip5-cover and no surfaces named, renders the cover face plus
the tall-layout stress set (the panels that must also survive on a square
panel so nothing ships that only looks right unfolded).
Serves the project root itself so the page can load the ROM's own shader
from vendor/.
"""
import argparse, functools, http.server, os, subprocess, sys, threading
from playwright.sync_api import sync_playwright

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
OUT = os.path.join(ROOT, "design/render/out")
DEVICES = {
    "s10": (412, 870, 3),
    "flip5-main": (360, 880, 3),
    "flip5-cover": (360, 374, 2),
}
ALL = ["home", "lock", "deck", "shade", "volume", "power", "voice", "drawer", "recents", "settings", "keys", "welcome", "edge",
       "studio", "ambient", "capsule", "auras", "cover"]
COVER_STRESS = ["cover", "home", "lock", "deck", "shade"]

class Quiet(http.server.SimpleHTTPRequestHandler):
    def log_message(self, *a): pass

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--device", default="s10", choices=list(DEVICES))
    ap.add_argument("surfaces", nargs="*")
    a = ap.parse_args()
    names = a.surfaces or (COVER_STRESS if a.device == "flip5-cover" else ALL)
    d = OUT if a.device == "s10" else os.path.join(OUT, a.device)
    os.makedirs(OUT, exist_ok=True)
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=ROOT))
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    w, h, scale = DEVICES[a.device]
    with sync_playwright() as p:
        b = p.chromium.launch(args=["--no-sandbox", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"])
        pg = b.new_page(viewport={"width": w, "height": h}, device_scale_factor=scale)
        for name in names:
            port = srv.server_address[1]
            pg.goto(f"http://127.0.0.1:{port}/design/render/index.html?s={name}&d={a.device}")
            pg.wait_for_function("document.title !== 'Vanta render'", timeout=600_000)
            pg.wait_for_timeout(300)
            path = os.path.join(d, f"{name}.png")
            pg.locator("#phone").screenshot(path=path, animations="disabled")
            print(path, flush=True)
        b.close()
    sheet = os.path.join(d, "sheet.png")
    paths = [os.path.join(d, f"{n}.png") for n in names]
    subprocess.run(["montage"] + paths + ["-tile", "5x", "-geometry", "+4+4", "-background", "#050607", sheet], check=False)
    print(sheet, flush=True)

if __name__ == "__main__":
    main()
