"""Screenshots of the one visual surface, the sheet, taken from a real terminal.

Builds nulltest, makes the CARD.md test files from the built binary, runs real
commands in tmux panes (80 columns for a desktop, 66 for a phone, the sheet's
64 plus a margin), keeps each pane as tmux printed it in out/pane-*.txt and
draws those characters as they are to shots/. Needs go, tmux and Playwright
for Python. Run from the project folder: python shots.py
"""

import html
import os
import shutil
import subprocess
import tempfile
import time

from playwright.sync_api import sync_playwright

TMUX = ["tmux", "-L", "nulltest-shots", "-f", "/dev/null"]
here = os.getcwd()
work = tempfile.mkdtemp()

SCENES = {
    "different": ["./nulltest real.bin flip1.bin; echo $?"],
    "identical": ["./nulltest real.bin same.bin; echo $?"],
    "insertion": ["./nulltest -q real.bin ins.bin; echo $?"],
    "single": ["./nulltest README.md; echo $?"],
    "errors": [
        "./nulltest nosuch.bin real.bin; echo $?",
        "./nulltest -q real.bin big.bin; echo $?",
        "./nulltest -s 1 real.bin same.bin; echo $?",
        "./nulltest -q real.bin same.bin >/dev/null && echo same",
    ],
}


def tmux(*args: str) -> str:
    return subprocess.run(TMUX + list(args), check=True, capture_output=True, text=True).stdout


def prepare() -> None:
    subprocess.run(["go", "build", "-o", f"{work}/nulltest", "."], check=True)
    shutil.copy("README.md", work)
    real = open(f"{work}/nulltest", "rb").read()
    flip = bytearray(real)
    flip[100000] ^= 1
    files = {
        "real.bin": real,
        "same.bin": real,
        "flip1.bin": bytes(flip),
        "ins.bin": real[:100000] + bytes([real[100000] ^ 1]) + real[100000:],
    }
    for name, data in files.items():
        with open(f"{work}/{name}", "wb") as f:
            f.write(data)
    with open(f"{work}/big.bin", "wb") as f:
        f.truncate(257 << 20)


def pane(name: str, cols: int, rows: int, commands: list[str]) -> str:
    env = f"env -i HOME={work} PATH={os.environ['PATH']} TERM=xterm-256color"
    tmux("new-session", "-d", "-s", name, "-x", str(cols), "-y", str(rows), f"{env} bash --norc --noprofile -i")
    time.sleep(0.5)
    tmux("send-keys", "-t", name, f"cd {work}; PS1='$ '; clear", "Enter")
    time.sleep(0.5)
    for c in commands:
        tmux("send-keys", "-t", name, c, "Enter")
        for _ in range(150):  # the sheet prints at once; wait for the prompt to return
            time.sleep(0.1)
            if tmux("capture-pane", "-p", "-t", name).rstrip().endswith("$"):
                break
    text = tmux("capture-pane", "-p", "-t", name)
    tmux("kill-session", "-t", name)
    return "\n".join(line.rstrip() for line in text.rstrip().split("\n"))


THEMES = {"light": ("#FCF0DD", "#1A1A1A"), "dark": ("#1A1A1A", "#FCF0DD")}


def page(text: str, theme: str, cols: int, width: int) -> str:
    bg, ink = THEMES[theme]
    pad = 16
    size = 16 if width > 900 else round((width - 2 * pad) / (cols * 0.602), 1)
    return f"""<!doctype html><meta charset="utf-8"><title>nulltest</title>
<style>html,body{{margin:0;background:{bg};color:{ink}}}
pre{{margin:0;padding:{pad}px;font:{size}px/1.3 "DejaVu Sans Mono",ui-monospace,Menlo,monospace;white-space:pre}}</style>
<pre>{html.escape(text)}</pre>"""


def main() -> None:
    prepare()
    os.makedirs("shots", exist_ok=True)
    os.makedirs("out", exist_ok=True)
    subprocess.run(TMUX + ["kill-server"], capture_output=True)
    sizes = {"desktop": (1280, 900, 80, 30), "phone": (390, 844, 66, 30)}
    with sync_playwright() as p:
        browser = p.chromium.launch()
        for label, (w, h, cols, rows) in sizes.items():
            for scene, commands in SCENES.items():
                text = pane(scene, cols, rows, commands)
                with open(f"out/pane-{scene}-{label}.txt", "w") as f:
                    f.write(text + "\n")
                for theme in THEMES:
                    pg = browser.new_page(viewport={"width": w, "height": h})
                    errors: list[str] = []
                    pg.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
                    pg.set_content(page(text, theme, cols, w))
                    wide = pg.evaluate("document.documentElement.scrollWidth")
                    shot = f"shots/{scene}-{label}-{theme}.png"
                    pg.screenshot(path=shot)
                    print(f"{shot} {w}x{h}, page width {wide}, console errors {errors}")
                    pg.close()
        browser.close()
    shutil.rmtree(work)


main()
