"""Turns the real tmux captures in out/pane-*.ans (left by acceptance.sh, taken
with capture-pane -e -N) into out/<name>.html pages for screenshots. Nothing is
drawn by hand: every character and colour comes from the captured pane.

From this folder: uv run python shots.py
"""

import html
import re
from pathlib import Path

OUT = Path(__file__).resolve().parent / "out"
SIZES = {"desk": (14, "96 columns"), "phone": (11, "50 columns")}
CAPTIONS = {
    "install": "itemised bun install --offline",
    "remove": "itemised rm -rf node_modules",
    "empty": "itemised ls",
}
GROUND, PANE, TEXT = "#FCF0DD", "#1A1A1A", "#E9E4DA"
ANSI = [
    "#1A1A1A", "#F08A7C", "#6FBF7B", "#E0AE4E", "#9DA7EA", "#F4B6C3", "#96AA9F", "#E9E4DA",
    "#5B5B5B", "#F08A7C", "#6FBF7B", "#E0AE4E", "#9DA7EA", "#F4B6C3", "#96AA9F", "#FFFFFF",
]  # fmt: skip

PAGE = """<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Itemised</title>
<style>
:root {{ --ground: {ground}; --pane: {pane}; --text: {text}; --lh: {lh}px; }}
html {{ background: var(--ground); }}
body {{ margin: 0; padding: 24px 16px; color: #1A1A1A;
  font: 12px/1.5 ui-sans-serif, system-ui, sans-serif; }}
figure {{ margin: 0 auto; width: max-content; max-width: 100%; }}
.pane {{ background: var(--pane); color: var(--text); padding: 12px 10px;
  font: {font}px/var(--lh) ui-monospace, "DejaVu Sans Mono", Menlo, monospace;
  overflow: hidden; }}
.l {{ height: var(--lh); white-space: pre; }}
.l span {{ display: inline-block; height: var(--lh); vertical-align: top; }}
figcaption {{ margin-top: 10px; color: #5B5B5B; }}
</style>
<figure>
<div class="pane">
{lines}
</div>
<figcaption>{caption}</figcaption>
</figure>
"""


def colour(p: list[int], i: int) -> tuple[str | None, int]:
    """The colour named by an extended 38/48 sequence at p[i], and its length."""
    if p[i + 1] == 2:
        return "#{:02X}{:02X}{:02X}".format(*p[i + 2 : i + 5]), 5
    n = p[i + 2]
    if n < 16:
        return ANSI[n], 3
    if n >= 232:
        g = 8 + 10 * (n - 232)
        return f"#{g:02X}{g:02X}{g:02X}", 3
    n -= 16
    r, g, b = (0 if c == 0 else 55 + 40 * c for c in (n // 36, n // 6 % 6, n % 6))
    return f"#{r:02X}{g:02X}{b:02X}", 3


def page(ans: str, font: int, caption: str) -> str:
    fg = bg = None
    bold = dim = False
    rows = ans.rstrip("\n").split("\n")
    while rows and not re.sub(r"\x1b\[[0-9;:]*m", "", rows[-1]).strip():
        rows.pop()
    out = []
    for row in rows:
        spans = []
        for m in re.finditer(r"\x1b\[([0-9;:]*)m|([^\x1b]+)", row):
            if m.group(2) is not None:
                css = [f"color:{fg}" if fg else "", f"background:{bg}" if bg else ""]
                css += ["font-weight:700" if bold else "", "opacity:.62" if dim else ""]
                style = ";".join(c for c in css if c)
                text = html.escape(m.group(2))
                spans.append(f'<span style="{style}">{text}</span>' if style else text)
                continue
            p = [int(x or 0) for x in re.split("[;:]", m.group(1))]
            i = 0
            while i < len(p):
                c = p[i]
                step = 1
                if c == 0:
                    fg = bg = None
                    bold = dim = False
                elif c == 1:
                    bold = True
                elif c == 2:
                    dim = True
                elif c == 22:
                    bold = dim = False
                elif 30 <= c <= 37 or 90 <= c <= 97:
                    fg = ANSI[c - 30 if c < 90 else c - 82]
                elif 40 <= c <= 47 or 100 <= c <= 107:
                    bg = ANSI[c - 40 if c < 100 else c - 92]
                elif c == 39:
                    fg = None
                elif c == 49:
                    bg = None
                elif c in (38, 48):
                    value, step = colour(p, i)
                    if c == 38:
                        fg = value
                    else:
                        bg = value
                i += step
        # a plain run is wrapped too, so every cell sits on the same baseline
        line = "".join(
            s if s.startswith("<span") else f"<span>{s}</span>" for s in spans
        )
        out.append(f'<div class="l">{line}</div>')
    return PAGE.format(
        ground=GROUND,
        pane=PANE,
        text=TEXT,
        lh=round(font * 1.3),
        font=font,
        lines="\n".join(out),
        caption=html.escape(caption),
    )


def main() -> None:
    for path in sorted(OUT.glob("pane-*.ans")):
        _, what, size = path.stem.split("-")
        font, cols = SIZES[size]
        caption = f"{CAPTIONS[what]}. A real tmux pane, {cols}, captured after the run."
        target = OUT / f"{what}-{size}.html"
        target.write_text(page(path.read_text(encoding="utf-8"), font, caption))
        print(f"wrote {target.name}")


if __name__ == "__main__":
    main()
