"""Writes out/<surface>-<size>.html: real tmux captures of margin, for screenshots.

Run where tmux, bash and git exist: uv run python shots.py
Every page is the capture of a real pane running the real tool. Nothing is drawn by hand.
"""

import html
import os
import shlex
import shutil
import subprocess
import tempfile
import termios
import time

HERE = os.path.dirname(os.path.abspath(__file__))
SIZES = {"1280": (96, 30, 15), "390": (40, 38, 13)}  # columns, rows, font px
SUBJECT = "Read the window size at each repaint, not once at start"

PAGE = """<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Margin Bell</title>
<style>
:root {{ --ground: #FCF0DD; --ink: #1A1A1A; --soft: #5B5B5B; }}
body {{ margin: 0; background: var(--ground); color: var(--ink);
  font: {font}px/1.35 ui-monospace, "DejaVu Sans Mono", Menlo, Consolas, monospace; }}
figure {{ margin: 24px auto; width: max-content; max-width: calc(100vw - 32px); }}
pre {{ margin: 0; padding: 10px 12px; border: 1px solid var(--ink); font: inherit;
  width: {cols}ch; overflow: hidden; }}
.cursor {{ background: var(--ink); color: var(--ground); }}
figcaption {{ margin-top: 10px; max-width: {cols}ch; font: 12px/1.5 system-ui, sans-serif;
  color: var(--soft); }}
</style>
<figure>
<pre>{screen}</pre>
<figcaption>{caption}</figcaption>
</figure>
"""


class Pane:
    def __init__(self, cols, rows, cwd, env):
        self.sock = os.path.join(cwd, "tmux.sock")
        shell = ["env", *(f"{k}={v}" for k, v in env.items()), "bash", "--norc", "--noprofile"]
        self.t("-f", "/dev/null", "new-session", "-d", "-x", str(cols), "-y", str(rows),
               "-c", cwd, shlex.join(shell))
        self.t("set-option", "-g", "status", "off")
        time.sleep(0.5)

    def t(self, *args):
        return subprocess.run(["tmux", "-S", self.sock, *args], check=True,
                              capture_output=True, text=True).stdout

    def run(self, command, wait=1.0):
        self.t("send-keys", "-l", command)
        self.t("send-keys", "Enter")
        time.sleep(wait)

    def wait_for_margin(self, timeout=10.0):
        """After Enter: bash hands the terminal over cooked, then margin turns ECHO off."""
        path = self.t("display-message", "-p", "#{pane_tty}").strip()
        deadline = time.monotonic() + timeout
        for want in (True, False):
            while time.monotonic() < deadline:
                fd = os.open(path, os.O_RDONLY | os.O_NOCTTY)
                echo = bool(termios.tcgetattr(fd)[3] & termios.ECHO)
                os.close(fd)
                if echo == want:
                    break
                time.sleep(0.002)
        time.sleep(0.1)

    def typed(self, text, pause=0.06):
        for c in text:
            self.t("send-keys", "-l", c)
            time.sleep(pause)

    def screen(self):
        rows = self.t("capture-pane", "-p").split("\n")[:-1]  # every row, empty ones too
        x, y = (int(v) for v in self.t("display-message", "-p", "#{cursor_x} #{cursor_y}").split())
        row = rows[y].ljust(x + 1)
        rows[y] = row[:x] + "\0" + row[x] + "\1" + row[x + 1:]
        text = html.escape("\n".join(r.rstrip() for r in rows))
        return text.replace("\0", '<span class="cursor">').replace("\1", "</span>")

    def close(self):
        subprocess.run(["tmux", "-S", self.sock, "kill-server"], capture_output=True)


def page(name, size, screen, caption):
    cols, _, font = SIZES[size]
    os.makedirs(os.path.join(HERE, "out"), exist_ok=True)
    with open(os.path.join(HERE, "out", f"{name}-{size}.html"), "w") as f:
        f.write(PAGE.format(font=font, cols=cols, screen=screen, caption=html.escape(caption)))


def surfaces(size):
    cols, rows, _ = SIZES[size]
    work = tempfile.mkdtemp()
    try:
        bindir, repo = os.path.join(work, "bin"), os.path.join(work, "repo")
        os.mkdir(bindir)
        shutil.copy(os.path.join(HERE, "margin.py"), os.path.join(bindir, "margin"))
        os.chmod(os.path.join(bindir, "margin"), 0o755)
        subprocess.run(["git", "init", "-q", "-b", "main", repo], check=True)
        env = {"PS1": "$ ", "PATH": bindir + os.pathsep + os.environ["PATH"],
               "GIT_CONFIG_GLOBAL": os.path.join(work, "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1",
               "GIT_AUTHOR_NAME": "margin", "GIT_AUTHOR_EMAIL": "margin@example.invalid",
               "GIT_COMMITTER_NAME": "margin", "GIT_COMMITTER_EMAIL": "margin@example.invalid"}
        with open(os.path.join(HERE, "README.md")) as f:
            alias = next(line for line in f if line.startswith("git config --global alias.cm"))
        subprocess.run(["sh", "-c", alias], env=dict(os.environ, **env), check=True)

        pane = Pane(cols, rows, repo, env)
        try:
            pane.run('git commit --allow-empty -m "$(margin 50)"', wait=0)
            pane.wait_for_margin()
            pane.typed(SUBJECT)
            time.sleep(0.3)
            page("typing", size, pane.screen(),
                 "Fig. 1. A commit subject typed past a margin of 50, before Return. "
                 "The bells are not shown.")
            pane.t("send-keys", "Enter")
            time.sleep(1.0)
            pane.run("git cm --allow-empty", wait=0)
            pane.wait_for_margin()
            pane.typed("Half a thought")
            pane.t("send-keys", "C-c")
            time.sleep(1.0)
            pane.run("margin --ring")
            pane.run("margin abc")
            pane.run("git log --oneline")
            page("session", size, pane.screen(),
                 "Fig. 2. The same terminal afterwards: the commit, a withdrawn line, "
                 "the bell check, a usage error, and the subject where it circulates.")
            pane.run("clear; margin --help")
            page("help", size, pane.screen(), "Fig. 3. margin --help.")
        finally:
            pane.close()
    finally:
        shutil.rmtree(work, True)


if __name__ == "__main__":
    for size in SIZES:
        surfaces(size)
        print("wrote", *(f"out/{n}-{size}.html" for n in ("typing", "session", "help")))
