"""Screenshots of the terminal surfaces, taken from a real terminal.

Types each command into a real bash in a tmux pane at a desktop and a phone
width, keeps the pane as tmux printed it (out/screen-*.ans, bold included), and
draws those cells as they are, in a monospace face, to shots/. Needs tmux, uv
and Playwright for Python; run it from the project folder.
"""

import html
import os
import re
import subprocess
import time

from playwright.sync_api import sync_playwright

TMUX = ["tmux", "-L", "corrigenda-shots", "-f", "/dev/null"]
SURFACES = {
    "own": "uv run corrigenda.py",
    "page": "uv run corrigenda.py fixtures/zsh-extended.hist",
    "stands": "uv run corrigenda.py fixtures/bash-plain-retired.hist",
    "aliases": "uv run corrigenda.py --aliases fixtures/zsh-extended.hist",
    "missing": "uv run corrigenda.py ~/.zsh_history",
}
SIZES = {"desktop": (1280, 900, 120, 40, 16), "phone": (390, 844, 46, 46, 13)}
THEMES = {"light": ("#FFFFFF", "#1A1A1A"), "dark": ("#121212", "#E6E6E6")}


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


def screen(command, cols, rows):
    """The pane after typing command into a fresh bash: the visible screen, and the scrollback from the command on."""
    path = os.path.expanduser("~/.local/bin") + ":" + os.environ["PATH"]
    # HISTFILE= keeps this bash from writing a history of its own anywhere.
    tmux("new-session", "-d", "-s", "s", "-x", str(cols), "-y", str(rows), "-c", os.getcwd(),
         "env", "-i", f"HOME={os.environ['HOME']}", f"PATH={path}", "TERM=xterm-256color",
         "LANG=C.UTF-8", "PS1=$ ", "HISTFILE=", "bash", "--norc", "--noprofile", "-i")
    time.sleep(0.8)
    tmux("send-keys", "-t", "s", "clear", "Enter")
    time.sleep(0.5)
    tmux("send-keys", "-t", "s", "-l", command)
    tmux("send-keys", "-t", "s", "Enter")
    for _ in range(100):  # until the prompt is back on its own line, at most 30 s
        time.sleep(0.3)
        visible = tmux("capture-pane", "-e", "-p", "-t", "s")
        if visible.rstrip().split("\n")[-1].strip() == "$":
            break
    else:
        raise SystemExit(f"the prompt did not come back after: {command}")
    whole = tmux("capture-pane", "-e", "-p", "-S", "-", "-t", "s")
    tmux("kill-server")
    whole = whole[whole.index("$ uv run"):]  # from the typed command on
    return visible, whole


SGR = re.compile(r"\x1b\[([0-9;:]*)m")


def cells(ans):
    """tmux's own SGR output as spans; only bold is kept, since the page uses nothing else."""
    parts, bold, pos = [], False, 0
    for m in SGR.finditer(ans):
        parts.append((bold, ans[pos:m.start()]))
        params = m.group(1).split(";")
        if "1" in params:
            bold = True
        elif set(params) & {"", "0", "22"}:
            bold = False
        pos = m.end()
    parts.append((bold, ans[pos:]))
    return "".join(f"<b>{html.escape(t)}</b>" if b else html.escape(t) for b, t in parts)


def page(ans, theme, size):
    bg, ink = THEMES[theme]
    return f"""<!doctype html><meta charset="utf-8"><title>corrigenda</title>
<style>html,body{{margin:0;background:{bg};color:{ink}}}
pre{{margin:0;padding:12px;font:{size}px/1.35 "DejaVu Sans Mono",ui-monospace,Menlo,monospace;white-space:pre}}
b{{font-weight:bold}}</style>
<pre>{cells(ans.rstrip())}</pre>"""


def main():
    os.makedirs("shots", exist_ok=True)
    os.makedirs("out", exist_ok=True)
    subprocess.run(TMUX + ["kill-server"], capture_output=True)
    with sync_playwright() as p:
        browser = p.chromium.launch()
        for label, (w, h, cols, rows, font) in SIZES.items():
            for name, command in SURFACES.items():
                visible, whole = screen(command, cols, rows)
                with open(f"out/screen-{name}-{cols}.ans", "w") as f:
                    f.write(whole)
                for theme in THEMES if name == "page" else ["light"]:
                    pg = browser.new_page(viewport={"width": w, "height": h})
                    errors = []
                    pg.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
                    pg.set_content(page(visible, theme, font))
                    wide = pg.evaluate("document.documentElement.scrollWidth")
                    out = f"shots/{name}-{label}-{theme}.png"
                    pg.screenshot(path=out)
                    print(f"{out} {w}x{h}, {cols}x{rows} pane, page width {wide}, console errors {errors}")
                    pg.close()
        browser.close()


main()
