#!/usr/bin/env python3
"""Render Vanta Liquid (the ROM's live wallpaper shader) to PNGs, headless.

  wallpaper.py OUT.png W H [--time 14]                    one still
  wallpaper.py OUTDIR  W H --frames N [--fps 30] [--time 14]  a sequence, 0000.png ...
Uses design/render/wall.js, so these are the same pixels the design renders use.
"""
import argparse, base64, functools, http.server, os, threading
from playwright.sync_api import sync_playwright

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

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

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("out"); ap.add_argument("w", type=int); ap.add_argument("h", type=int)
    ap.add_argument("--time", type=float, default=14.0)
    ap.add_argument("--frames", type=int, default=0)
    ap.add_argument("--fps", type=float, default=30.0)
    a = ap.parse_args()
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=ROOT))
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    url = f"http://127.0.0.1:{srv.server_address[1]}/tools/preview/wall.html?w={a.w}&h={a.h}&t={a.time}"
    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": 64, "height": 64})
        pg.goto(url)
        pg.wait_for_function("document.title !== 'wall'", timeout=600_000)
        if pg.title() != "ready":
            raise SystemExit(pg.title())
        def grab(t, path):
            data = pg.evaluate(f"window.frame({t})")
            open(path, "wb").write(base64.b64decode(data.split(",", 1)[1]))
        if a.frames:
            os.makedirs(a.out, exist_ok=True)
            for i in range(a.frames):
                grab(a.time + i / a.fps, os.path.join(a.out, f"{i:04d}.png"))
        else:
            grab(a.time, a.out)
        b.close()
    print(a.out)

if __name__ == "__main__":
    main()
