"""Renders the terminal text that scripts/e2e.sh captured in out/ as
screenshots in shots/, at 1280x900 and 390x844. The tool has no surface
but the terminal, so each shot is that captured text set in monospace,
ink on a plain ground, nothing added."""

import html
from pathlib import Path

from playwright.sync_api import sync_playwright

SURFACES = {
    "notice": "out/notice.txt",
    "minutes-64col-pane": "out/tmux-64.txt",
    "rejections": "out/rejections.txt",
    "long-call-minutes": "out/big-minutes.txt",
}
SIZES = {"desktop": (1280, 900), "phone": (390, 844)}

PAGE = """<!doctype html><meta charset="utf-8">
<style>
html, body {{ margin: 0; background: #ffffff; color: #111111; }}
pre {{ margin: 0; padding: 16px; font: {size}px/1.35 ui-monospace, "DejaVu Sans Mono", monospace;
       white-space: pre-wrap; overflow-wrap: anywhere; }}
</style><pre>{text}</pre>"""


def font_px(width: int) -> float:
    # 64 columns plus the 16px gutters, monospace advance is about 0.6em
    return min(15.0, (width - 32) / 64 / 0.602)


with sync_playwright() as p:
    browser = p.chromium.launch()
    for name, src in SURFACES.items():
        text = Path(src).read_text().rstrip("\n")
        for label, (w, h) in SIZES.items():
            page = browser.new_page(viewport={"width": w, "height": h})
            page.set_content(PAGE.format(size=f"{font_px(w):.2f}", text=html.escape(text)))
            over = page.evaluate("document.documentElement.scrollWidth > innerWidth")
            out = f"shots/{name}-{label}.png"
            page.screenshot(path=out)
            print(f"{out} {w}x{h} horizontal overflow: {over}")
            page.close()
    browser.close()
