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

Types each command into a real bash in a tmux pane (truecolor, at a desktop and
a phone width), keeps the pane as tmux printed it (out/screen-*.ans), and draws
those cells, bold, dim and the one brick rule included, in a monospace face
with headless Chromium. Needs tmux, uv and Playwright for Python.

Run from the project folder: python shots.py REPO
REPO is a real git repository; it is only read.
"""

import html
import os
import re
import subprocess
import sys
import tempfile
import time

from playwright.sync_api import sync_playwright

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = sys.argv[1]
TMUX = ["tmux", "-L", "emporium-shots", "-f", "/dev/null"]
# name: (folder, typed command)
SURFACES = {
    "report": (REPO, "emporium"),
    "self": (HERE, "uv run emporium.py"),
    "filter": (REPO, "emporium g"),
    "classes": (REPO, "emporium --classes"),
    "help": (REPO, "emporium --help"),
    "unknown": (REPO, "emporium dogs"),
}
# label: (viewport w, h, pane cols, rows, font px)
SIZES = {"1280": (1280, 900, 148, 52, 14), "390": (390, 844, 46, 52, 13)}
THEMES = {"light": ("#FFFFFF", "#1A1A1A"), "dark": ("#141414", "#E4E4E4")}


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


def screen(cwd, command, cols, rows, bindir):
    """The visible pane after typing command into a fresh bash."""
    path = bindir + ":" + os.path.expanduser("~/.local/bin") + ":" + os.environ["PATH"]
    tmux("new-session", "-d", "-s", "s", "-x", str(cols), "-y", str(rows), "-c", cwd,
         "env", "-i", f"HOME={os.environ['HOME']}", f"PATH={path}", "TERM=xterm-256color",
         "COLORTERM=truecolor", "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):
        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}")
    tmux("kill-server")
    return visible


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


def cells(ans):
    """tmux's SGR output as spans: bold, dim and a 24-bit foreground."""
    out, pos, bold, dim, fg = [], 0, False, False, None

    def span(text):
        if not text:
            return
        style = ";".join(s for s in ("font-weight:bold" if bold else "", "opacity:.62" if dim else "",
                                     f"color:rgb({fg})" if fg else "") if s)
        out.append(f'<span style="{style}">{html.escape(text)}</span>' if style else html.escape(text))

    for m in SGR.finditer(ans):
        span(ans[pos:m.start()])
        ps = [int(x or 0) for x in m.group(1).replace(":", ";").split(";")]
        i = 0
        while i < len(ps):
            p = ps[i]
            if p == 0:
                bold = dim = False
                fg = None
            elif p == 1:
                bold = True
            elif p == 2:
                dim = True
            elif p == 22:
                bold = dim = False
            elif p == 39:
                fg = None
            elif p == 38 and i + 4 < len(ps) and ps[i + 1] == 2:
                fg = ",".join(map(str, ps[i + 2:i + 5]))
                i += 4
            i += 1
        pos = m.end()
    span(ans[pos:])
    return "".join(out)


def page(ans, theme, size):
    bg, ink = THEMES[theme]
    return f"""<!doctype html><meta charset="utf-8"><title>emporium index</title>
<style>html,body{{margin:0;background:{bg};color:{ink}}}
pre{{margin:0;padding:12px;font:{size}px/1.2 "DejaVu Sans Mono",ui-monospace,Menlo,monospace;white-space:pre}}</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 tempfile.TemporaryDirectory() as bindir, sync_playwright() as p:
        with open(os.path.join(bindir, "emporium"), "w") as f:  # the tool under its own name
            f.write(f'#!/bin/sh\nexec uv run --quiet "{HERE}/emporium.py" "$@"\n')
        os.chmod(os.path.join(bindir, "emporium"), 0o755)
        browser = p.chromium.launch()
        for label, (w, h, cols, rows, font) in SIZES.items():
            for name, (cwd, command) in SURFACES.items():
                visible = screen(cwd, command, cols, rows, bindir)
                with open(f"out/screen-{name}-{label}.ans", "w") as f:
                    f.write(visible)
                for theme in THEMES if name in ("report", "self") 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")
                    tall = pg.evaluate("document.documentElement.scrollHeight")
                    out = f"shots/{name}-{label}-{theme}.png"
                    pg.screenshot(path=out)
                    print(f"{out} {w}x{h}, pane {cols}x{rows}, page {wide}x{tall}, console errors {errors}")
                    pg.close()
        browser.close()


main()
