"""End to end acceptance run for firsts.py (CARD.md checks 2 to 10).

Run in this folder on a Linux box with uv and tmux: uv run python e2e.py
Every book it writes lives in a fresh temporary directory. It writes out/e2e.log,
tmux captures in out/term/*.txt and a page per capture in out/term/*.html.
"""

import ast
import hashlib
import html
import os
import re
import subprocess
import sys
import tempfile
import time
from datetime import date
from pathlib import Path

ROOT = Path(__file__).resolve().parent
OUT = ROOT / "out"
TERM = OUT / "term"
TMP = Path(tempfile.mkdtemp(prefix="firsts-e2e-"))
BIN = TMP / "bin"
MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
HEADER = "# First occurrences. One line per entry. A line is never changed."
TAIL = "This tool has changed no line."
LOG = []
STATS = {"commands": 0, "prefix": 0, "refused_unchanged": 0}


def log(*lines):
    for line in lines:
        LOG.append(line)
        print(line)


def check(cond, what):
    if not cond:
        log(f"FAILED: {what}")
        (OUT / "e2e.log").write_text("\n".join(LOG) + "\n")
        sys.exit(1)
    log(f"  ok  {what}")


def shell(cmd):
    return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout.strip()


T = shell("date +%F")
Y = int(T[:4])
DOY = int(shell("date +%j"))
TD = date.fromisoformat(T)
H = f"{TD.day} {MONTHS[TD.month - 1]} {Y}"
HD = f"{TD.day} {MONTHS[TD.month - 1]}"
CELL_TODAY = f"{MONTHS[TD.month - 1]} {TD.day:>2}"


def env(colour=False):
    e = {k: v for k, v in os.environ.items() if k not in ("NO_COLOR", "COLORTERM", "FIRSTS_FILE")}
    e.update(LC_ALL="C", PATH=f"{BIN}:{os.environ['PATH']}")
    if colour:
        e["COLORTERM"] = "truecolor"
    else:
        e["NO_COLOR"] = "1"
    return e


def read(path):
    return path.read_bytes() if path.exists() else None


def run(book, *args, stdin=None, via="uv", colour=False):
    """Run one command against one book and hold check 3 on its bytes."""
    before = read(book)
    cmd = ["uv", "run", "firsts.py", *args] if via == "uv" else ["firsts", *args]
    e = env(colour)
    e["FIRSTS_FILE"] = str(book)
    r = subprocess.run(cmd, cwd=ROOT if via == "uv" else TMP, input=stdin, capture_output=True, text=True, env=e)
    after = read(book)
    STATS["commands"] += 1
    shown = " ".join(cmd[2:] if via == "uv" else cmd)
    log(f"$ {'uv run ' if via == 'uv' else ''}{shown}" + (f"  <<< {stdin!r}" if stdin else "") + f"   [{book.name}, exit {r.returncode}]")
    for line in r.stdout.rstrip("\n").split("\n") if r.stdout else []:
        log(f"  | {line}")
    for line in r.stderr.rstrip("\n").split("\n") if r.stderr else []:
        log(f"  ! {line}")
    if before is not None:
        check(after is not None and after[:len(before)] == before, f"check 3: earlier {len(before)} bytes are a prefix of the later {len(after or b'')}")
        STATS["prefix"] += 1
    if r.returncode != 0:
        check(after == before, "check 3: refused command left the file identical")
        STATS["refused_unchanged"] += 1
    return r.returncode, r.stdout, r.stderr


def table_part(out):
    """Header and row lines: from the line after the path to the first blank line."""
    lines = out.split("\n")
    start = next(i for i, l in enumerate(lines) if l.startswith(" ") and re.fullmatch(r"[0-9]{4}", (l.split() or [""])[0]))
    end = lines.index("", start)
    return lines[start:end]


def grid(out):
    """(pad, years, rows) where each row is (label, [nine-character cells])."""
    lines = table_part(out)
    header = lines[0]
    pad = len(header) - len(header.lstrip(" ")) - 1
    years = [int(y) for y in header.split()]
    for i, y in enumerate(years):
        check(header[pad + 1 + 9 * i:pad + 5 + 9 * i] == str(y), f"year {y} sits above the first character of its column")
    rows = []
    for line in lines[1:]:
        full = line.ljust(pad + 9 * len(years))
        rows.append((full[:pad].rstrip(), [full[pad + 9 * i:pad + 9 * (i + 1)] for i in range(len(years))]))
    return pad, years, rows


CELL = re.compile(r"^([ ]{9}|[ \[]([A-Z][a-z]{2} [ 0-9][0-9]| {0,5}[0-9]{1,3})[ \]][ *])$")


def how(gap):
    if gap == 0:
        return "on the same day"
    n = abs(gap)
    return f"{n} day{'' if n == 1 else 's'} {'earlier' if gap < 0 else 'later'}"


def check_2():
    log("", "CHECK 2: empty first run, first add, header, help")
    book = TMP / "book.txt"
    status, out, err = run(book)
    empty = ["Nothing entered.", "A first goes in with: uv run firsts.py add <event>",
             "Years already behind you go in with: uv run firsts.py backfill"]
    check(status == 0 and out.rstrip("\n").split("\n") == empty, "three-line empty message names uv run firsts.py, exit 0")
    check(not book.exists(), "the empty run did not create the file")
    status, out, _ = run(book, via="firsts")
    check(out.rstrip("\n").split("\n") == [l.replace("uv run firsts.py", "firsts") for l in empty] and "uv run" not in out,
          "through the symlink the same message names firsts and not uv run")
    status, out, _ = run(book, "add", "first", "swallow")
    lines = book.read_text().split("\n")
    check(lines == [HEADER, f"# Opened {T}.", f"{T} | seen | swallow", ""], "new file: header, # Opened today, one entry dated today")
    check(out.split("\n")[0] == f"Entered. swallow, {H}, seen. Day {DOY}.", f"entered line with day {DOY} (date +%j)")
    status, out, _ = run(book)
    _, years, rows = grid(out)
    check(years == [Y] and [r[0] for r in rows] == ["swallow"], "one column for the current year, one row")
    check(out.rstrip("\n").split("\n")[-1] == f"Book opened {H}. 1 entry, 0 of them older than the book. {TAIL}", "colophon for one entry")
    touched = TMP / "touched.txt"
    touched.touch()
    run(touched, "add", "first", "swallow")
    check(touched.read_text().split("\n")[:3] == [HEADER, f"# Opened {T}.", f"{T} | seen | swallow"], "zero-byte file gets the same two header lines and the entry")
    _, out, _ = run(book, "--help")
    check(out.startswith("usage: uv run firsts.py"), "uv run firsts.py --help shows usage: uv run firsts.py")
    check(out.rstrip("\n").split("\n")[-2:] == ["The file is yours. This tool only adds to it.", "normal is dead"], "help ends with the two closing lines")
    _, out, _ = run(book, "--help", via="firsts")
    check(out.startswith("usage: firsts"), "firsts --help shows usage: firsts")
    check(out.rstrip("\n").split("\n")[-2:] == ["The file is yours. This tool only adds to it.", "normal is dead"], "symlink help ends with the two closing lines")
    status, out, err = run(book, "--days", via="firsts")
    check(status != 0 and "usage: firsts" in err and not out, "firsts --days exits non-zero with the usage line and no table")
    return book


def check_4(book):
    log("", "CHECK 4: refusal")
    status, out, err = run(book, "add", "swallow")
    check(status != 0 and "already entered" in err and "The first is final." in err, "repeat add refused with already entered, The first is final.")
    check(f"swallow, {Y}: already entered, {HD}. The first is final." in err, "refusal names the existing date")
    check(f"To note a correction: uv run firsts.py erratum swallow {Y} <text>" in err, "remedy line names uv run firsts.py")
    status, _, err = run(book, "add", "swallow", via="firsts")
    check(status != 0 and f"To note a correction: firsts erratum swallow {Y} <text>" in err, "through the symlink the remedy names firsts")
    status, out, _ = run(book, "add", "swallow", "--date", "2024-03-29")
    check(status == 0 and out.startswith("Entered. swallow, 29 Mar 2024, seen. Day 89."), "a different year succeeds (29 Mar 2024 is day 89)")
    status, _, err = run(book, "add", "First", "Swallows")
    check(status != 0 and "already entered" in err, "First Swallows the same year is the same event and is refused")
    status, _, err = run(book, "add", "frost", "--date", f"{Y + 1}-04-11")
    check(status != 0 and f"11 Apr {Y + 1} has not happened." in err, "a future date is refused")
    status, _, err = run(book, "add", "frost", "--recalled")
    check(status != 0 and "needs --date" in err, "--recalled without --date is refused")


def check_5():
    log("", "CHECK 5: backfill")
    book = TMP / "backfill.txt"
    paste = "2025-04-02 swallow\n2024-03-29 swallow\n2025-11-02 frost\n2024-11-09 frost | I think the 9th\n"
    status, out, _ = run(book, "backfill", stdin=paste)
    check(status == 0 and out.split("\n")[0] == "4 lines entered.", "reports 4 lines entered")
    _, years, rows = grid(out)
    check(years == [2024, 2025], "columns for 2024 and 2025 only")
    filled = [c for _, cs in rows for c in cs if c.strip()]
    check(len(filled) == 4 and all(c.startswith("[") and c[7] == "]" for c in filled), "all four cells in square brackets")
    tail = out.rstrip("\n").split("\n")
    check("[ ] recalled" in tail and not any("erratum" in l or "Day counts" in l for l in tail), "key line is [ ] recalled and nothing else")
    check(tail[-1] == f"Book opened {H}. 4 entries, 4 of them older than the book. {TAIL}", "colophon: 4 entries, 4 of them older")
    check(book.read_text().count("| recalled |") == 4 and "| frost | I think the 9th" in book.read_text(), "stored as recalled, note kept")
    bad = "2025-05-01 cuckoo\nnot a date\n2025-04-02 swallow\n2025-05-03 cuckoo\n2099-01-01 frost\n"
    status, out, err = run(book, "backfill", stdin=bad)
    expected = ["Line 2 is not YYYY-MM-DD event.", "Line 3: swallow, 2025: already entered, 2 Apr. The first is final.",
                "Line 4: cuckoo, 2025: also given on line 1.", "Line 5: 1 Jan 2099 has not happened.", "Nothing written."]
    check(status != 0 and err.rstrip("\n").split("\n") == expected, "bad paste: every bad line listed by number, nothing written")
    seen = TMP / "seen.txt"
    status, out, _ = run(seen, "backfill", "--seen", stdin="2021-04-01 cuckoo\n")
    check(status == 0 and "2021-04-01 | seen | cuckoo" in seen.read_text(), "--seen stores seen")
    check("[" not in "\n".join(table_part(out)) and "recalled" not in out, "--seen prints no brackets and no recalled key")
    return book


def check_6(book):
    log("", "CHECK 6: comparison and errata")
    status, out, _ = run(book, "add", "swallow")
    lines = out.split("\n")
    check(lines[0] == f"Entered. swallow, {H}, seen. Day {DOY}.", "entered today")
    # Hand-checked day numbers: 2 Apr 2025 = 31+28+31+2 = 92; 29 Mar 2024 (leap) = 31+29+29 = 89.
    check(lines[1:3] == [f"2025: [2 Apr] (day 92). This entry is {how(DOY - 92)}.",
                         f"2024: [29 Mar] (day 89). This entry is {how(DOY - 89)}."], "one comparison line per earlier year, newest first, right difference")
    status, out, _ = run(book, "erratum", "swallow", str(Y), "the", "date", "was", "wrong")
    check(status == 0 and out.split("\n")[0] == f"Erratum filed against swallow, {Y}. The entry stands.", "erratum filed message")
    status, out, _ = run(book)
    _, years, rows = grid(out)
    swallow = dict(rows)["swallow"]
    check(swallow[years.index(Y)] == f" {CELL_TODAY} *", "cell keeps the original date and gains *")
    check(f"* swallow {Y}, filed {HD}: the date was wrong" in out, "errata block shows the text with the filed date")
    check(out.rstrip("\n").split("\n")[-1] == f"Book opened {H}. 5 entries, 4 of them older than the book. {TAIL}", "colophon: 5 entries, 4 older; the erratum is not counted")
    status, _, err = run(book, "erratum", "nothing", str(Y), "x")
    check(status != 0 and f"No entry for nothing, {Y}." in err, "erratum against a missing entry is refused")
    status, _, _ = run(book, "add", "wood", "anemone", "--date", "2025-04-20", "--recalled")
    check(status == 0, "add wood anemone --date 2025-04-20 --recalled")
    status, out, _ = run(book, "erratum", "wood", "anemone", "2025", "it", "was", "a", "wood", "sorrel")
    check(status == 0 and book.read_text().split("\n")[-2] == f"erratum | 2025 | wood anemone | filed {T} | it was a wood sorrel", "erratum files against the two-word event")
    status, _, err = run(book, "erratum", "swallow", str(Y))
    check(status != 0 and "Usage: uv run firsts.py erratum EVENT... YEAR TEXT..." in err, "erratum without text gives the usage line")
    status, _, _ = run(book, "erratum", "frost", "2025", "-the", "2nd,", "not", "the", "1st")
    check(status == 0 and book.read_text().split("\n")[-2].endswith("| -the 2nd, not the 1st"), "erratum text may begin with a hyphen")


def check_7(book):
    log("", "CHECK 7: plain text without the tool")
    text = book.read_text()
    log(*[f"  > {l}" for l in text.rstrip("\n").split("\n")])
    entry = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2} \| (seen|recalled) \| [^|]+?( \| .+)?$")
    erratum = re.compile(r"^erratum \| [0-9]{4} \| [^|]+ \| filed [0-9]{4}-[0-9]{2}-[0-9]{2} \| .+$")
    check(all(entry.match(l) or erratum.match(l) or l.startswith("# ") for l in text.rstrip("\n").split("\n")), "every line is an entry, an erratum or a comment")
    n = len(text.rstrip("\n").split("\n"))
    with open(book, "a") as f:  # a person typing two lines by hand
        f.write("2025-04-03 | seen | swallow\nswallow came back, forgot the date\n")
    held = read(book)
    status, out, err = run(book)
    check(status == 0 and "swallow" in out, "the table still prints")
    check(f"Line {n + 1} repeats swallow 2025. The first line stands." in err, f"stderr: line {n + 1} repeats")
    check(f"Line {n + 2} is not an entry. Left as it is." in err, f"stderr: line {n + 2} is not an entry")
    check(out.rstrip("\n").split("\n")[-1] == f"Book opened {H}. 6 entries, 5 of them older than the book. {TAIL}", "colophon counts only the entries the table is built from")
    check(read(book) == held, "the read left the file byte for byte unchanged")
    book.write_text("\n".join(l for l in book.read_text().split("\n") if not l.startswith("# Opened")))  # a person deleting the line by hand
    _, out, _ = run(book)
    check(out.rstrip("\n").split("\n")[-1] == f"6 entries. {TAIL}", "without # Opened the colophon is N entries.")


def tmux(*args):
    return subprocess.run(["tmux", "-L", "firsts", *args], capture_output=True, text=True).stdout


def pane(name, cols, rows, book, keys, colour, title):
    """Type keys into a real tmux pane and capture it, joined and as seen."""
    e = env(colour)
    e["FIRSTS_FILE"] = str(book)
    e["PS1"] = "$ "
    e["TERM"] = "screen-256color"
    tmux("kill-session", "-t", name)
    sets = " ".join(f"{k}={v!r}" for k, v in e.items() if k in ("PATH", "LC_ALL", "NO_COLOR", "COLORTERM", "FIRSTS_FILE", "PS1", "HOME", "TERM"))
    tmux("new-session", "-d", "-s", name, "-x", str(cols), "-y", str(rows), f"env -i {sets} bash --norc --noprofile -i")
    tmux("set-option", "-t", name, "status", "off")
    wait(name, lambda t: t.rstrip().endswith("$"))
    tmux("send-keys", "-t", name, "-l", f"cd {TMP}")
    tmux("send-keys", "-t", name, "Enter")
    tmux("send-keys", "-t", name, "-l", "clear")
    tmux("send-keys", "-t", name, "Enter")
    wait(name, lambda t: t.strip() == "$")
    for k in keys:
        if k == "C-d":
            tmux("send-keys", "-t", name, "C-d")
        else:
            tmux("send-keys", "-t", name, "-l", k)
            tmux("send-keys", "-t", name, "Enter")
        time.sleep(0.3)
    wait(name, lambda t: t.rstrip().endswith("\n$") and t.count("$ ") >= 1)
    joined = tmux("capture-pane", "-t", name, "-p", "-J")
    seen = tmux("capture-pane", "-t", name, "-p", "-e")
    tmux("kill-session", "-t", name)
    TERM.mkdir(parents=True, exist_ok=True)
    (TERM / f"{name}.txt").write_text(seen)
    (TERM / f"{name}.html").write_text(page(seen, cols, rows, title))
    log(f"  tmux {cols}x{rows} {name}:", *[f"  : {l}" for l in joined.rstrip("\n").split("\n")])
    return joined, seen


def wait(name, done, limit=60):
    end = time.time() + limit
    while time.time() < end:
        text = tmux("capture-pane", "-t", name, "-p")
        if done(text):
            time.sleep(0.2)
            return
        time.sleep(0.2)
    check(False, f"tmux pane {name} settled")


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


def painted(line):
    """The runs of characters printed in brick, read from tmux's own SGR output."""
    runs, on, current, pos = [], False, "", 0
    for m in list(SGR.finditer(line)) + [None]:
        text = line[pos:m.start()] if m else line[pos:]
        if on:
            current += text
        if m is None:
            break
        params = m.group(1)
        brick = "38;2;236;94;82" in params
        if brick and not on:
            on, current = True, ""
        elif on and (params in ("", "0", "39") or ("38;" in params and not brick)):
            runs.append(current)
            on = False
        pos = m.end()
    if on:
        runs.append(current)
    return [r for r in runs if r]


def page(text, cols, rows, title):
    out, on, pos = [], False, 0
    for m in list(SGR.finditer(text)) + [None]:
        chunk = html.escape(text[pos:m.start()] if m else text[pos:])
        out.append(chunk)
        if m is None:
            break
        params = m.group(1)
        if "38;2;236;94;82" in params and not on:
            out.append('<span class="b">')
            on = True
        elif on and (params in ("", "0", "39") or ("38;" in params and "236;94;82" not in params)):
            out.append("</span>")
            on = False
        pos = m.end()
    if on:
        out.append("</span>")
    body = "".join(out).rstrip("\n")
    body = "\n".join(l.rstrip() for l in body.split("\n"))
    return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>{html.escape(title)}</title>
<style>
:root {{ --paper: #FCF0DD; --ink: #1A1A1A; --soft: #5B5B5B; --brick: #EC5E52; }}
html, body {{ margin: 0; background: var(--paper); color: var(--ink); }}
body {{ padding: 24px 16px; font: 13px/1.4 ui-monospace, "DejaVu Sans Mono", Menlo, monospace; }}
figure {{ margin: 0 auto; width: max-content; max-width: 100%; }}
pre {{ margin: 0; padding: 12px; border: 1px solid var(--ink); background: #FFFDF8; line-height: 1.25;
       width: {cols}ch; min-height: {rows * 1.25}em; overflow: hidden; font: inherit; line-height: 1.25; }}
.b {{ color: var(--brick); }}
figcaption {{ margin-top: 8px; color: var(--soft); font-size: 11px; }}
</style></head>
<body><figure><pre id="p">{body}</pre><figcaption>{html.escape(title)}</figcaption></figure>
<script>
const fit = () => {{
  const room = document.documentElement.clientWidth - 32 - 26;
  const size = Math.min(16, room / ({cols} * 0.602));
  document.body.style.fontSize = size + "px";
}};
fit(); addEventListener("resize", fit);
</script></body></html>
"""


def check_8_9():
    log("", "CHECK 8: table layout in a real terminal")
    book = TMP / "firsts.txt"
    paste = ["2025-04-02 swallow", "2024-03-29 swallow", "2023-04-10 swallow | about the second week, I think", "2025-11-02 frost"]
    joined, _ = pane("backfill-80", 80, 24, book, ["firsts backfill", *paste, "C-d"], True, "FIG. 2: firsts backfill, pasted and ended with Ctrl-D. 80 x 24.")
    check("5 entries" not in joined and "4 lines entered." in joined and "Paste one line per entry: YYYY-MM-DD event. End with Ctrl-D." in joined, "interactive backfill prompts on a terminal and enters 4 lines")
    joined, _ = pane("add-80", 80, 24, book, ["firsts add first swallow --note over the mill pond"], True, "FIG. 3: firsts add, with every earlier year beside it. 80 x 24.")
    check(f"{T} | seen | swallow | over the mill pond" in book.read_text() and f"Entered. swallow, {H}, seen." in joined, "add with an unquoted --note")
    pane("refusal-80", 80, 24, book, ["firsts add swallow"], True, "FIG. 4: firsts add, a second time this year. 80 x 24.")
    pane("erratum-80", 80, 24, book, [f"firsts erratum swallow {Y} the date was wrong"], True, "FIG. 5: firsts erratum. 80 x 24.")

    joined, raw = pane("table-80-plain", 80, 24, book, ["firsts"], False, "Table at 80 columns, NO_COLOR=1.")
    lines = table_part(joined)
    check(len(lines[0].split()) >= 4, f"at least four years shown: {lines[0].split()}")
    check(all(len(l) <= 80 for l in lines), f"no header or row line exceeds 80 (widest {max(map(len, lines))})")
    _, years, rows = grid(joined)
    check(all(CELL.match(c) for _, cs in rows for c in cs), "every cell is nine characters and aligned under its year")
    check(any("[" in c for _, cs in rows for c in cs), "a recalled entry is in the table")
    check("\x1b" not in raw, "NO_COLOR=1: no escape bytes in the escaped capture")

    joined, raw = pane("table-40-plain", 40, 24, book, ["firsts"], False, "Table at 40 columns, NO_COLOR=1.")
    lines = table_part(joined)
    years40 = [int(y) for y in lines[0].split()]
    check(years40[0] > years[0] and years40[-1] == years[-1], f"oldest years dropped at 40: {years40}")
    check(all(len(l) <= 40 for l in lines), f"no header or row line exceeds 40 (widest {max(map(len, lines))})")
    hint = f"Years before {years40[0]} not shown. firsts table --from {years[0]}."
    check(hint in joined, f"hint names --from the oldest year in the file: {hint}")
    check("\x1b" not in raw, "NO_COLOR=1: no escape bytes at 40 columns")

    joined, _ = pane("from-40-plain", 40, 24, book, [f"firsts table --from {years[0]}"], False, "firsts table --from at 40 columns.")
    lines = table_part(joined)
    check([int(y) for y in lines[0].split()] == years, "--from prints every year")
    check(max(map(len, lines)) > 40, f"--from header and rows are wider than the terminal ({max(map(len, lines))} > 40)")

    log("", "CHECK 9: colour is conditional")
    joined, raw = pane("table-80", 80, 24, book, ["firsts"], True, "FIG. 1: firsts, the table at 80 columns on a truecolor terminal.")
    rows_raw = raw.rstrip("\n").split("\n")
    plain = [SGR.sub("", l) for l in rows_raw]
    start = plain.index(next(l for l in plain if l.startswith(" ") and l.split() and l.split()[0].isdigit()))
    end = plain.index("", start)
    check("38;2;236;94;82" in raw, "truecolor tty: brick 24-bit colour present")
    for l in rows_raw[start:end]:
        check(all(set(r) <= set("[]*") for r in painted(l)), f"row paints only brackets and *: {painted(l)}")
    for l, p in zip(rows_raw[end:], plain[end:]):
        runs = painted(l)
        if p.startswith("* ") and " filed " in p:
            check("".join(runs).strip() == p.strip(), f"errata block line is brick: {p}")
        elif p.startswith("[ ] recalled") or p.startswith("* erratum"):
            check(all(r.strip() in ("[ ]", "*", "[", "]") for r in runs), f"key paints only its marks: {runs}")
        elif p.startswith("Book opened") or p.startswith("Not yet") or p.startswith("Years before"):
            check(runs == [], f"no colour on: {p[:40]}")
    check(not any(painted(l) for l in rows_raw[:start]), "path line and prompt carry no colour")
    status, out, _ = run(book, "table", colour=True)
    check("\x1b" not in out and status == 0, "COLORTERM=truecolor but piped: no ANSI escapes")
    pane("table-40", 40, 24, book, ["firsts"], True, "FIG. 6: the same table on a 40 column terminal.")
    pane("days-80", 80, 24, book, ["firsts table --days"], True, "FIG. 7: firsts table --days.")
    pane("help-80", 80, 40, book, ["firsts --help"], True, "FIG. 8: firsts --help.")
    pane("empty-80", 80, 24, TMP / "nothing.txt", ["firsts"], True, "FIG. 0: firsts, before anything is entered.")


FORBIDDEN = ["os.remove", "os.replace", "os.unlink", "os.rename", "os.truncate", "truncate", "write_text",
             "write_bytes", "shutil.move", "shutil.rmtree", "shutil.copy", '"w"']


def check_10():
    log("", "CHECK 10: clean")
    files = ["firsts.py", "test_firsts.py", "README.md"]
    hits = shell("cd " + str(ROOT) + " && grep -rnE 'https?://' " + " ".join(files))
    check(hits == "", "no URL in firsts.py, test_firsts.py, README.md")
    shipped = [p for p in ROOT.iterdir() if p.suffix in (".py", ".md")]
    emoji = re.compile(r"[\u2014\u2013\U0001F000-\U0001FAFF\u2600-\u27BF\uFE0F]")
    check(all(not emoji.search(p.read_text()) for p in shipped), f"no em dash, en dash or emoji in {sorted(p.name for p in shipped)}")
    tree = ast.parse((ROOT / "firsts.py").read_text())
    mods = {a.name.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names}
    mods |= {n.module.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)}
    check(mods <= set(sys.stdlib_module_names), f"stdlib imports only: {sorted(mods)}")
    uses = {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute) and isinstance(n.value, ast.Name) and n.value.id == "shutil"}
    check(uses == {"get_terminal_size"}, f"shutil is used only for {sorted(uses)}")
    modes = []
    for n in ast.walk(tree):
        if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == "open":
            arg = n.args[1] if len(n.args) > 1 else next((k.value for k in n.keywords if k.arg == "mode"), None)
            modes.append(arg.value if isinstance(arg, ast.Constant) else None)
    check(modes and set(modes) <= {"r", "a"}, f"open( only with literal modes: {modes}")
    log("  " + shell(f"cd {ROOT} && grep -n 'open(' firsts.py"))
    source = (ROOT / "firsts.py").read_text()
    check(not [w for w in FORBIDDEN if w in source], "none of the forbidden write calls appear in firsts.py")
    book = TMP / "offline.txt"
    # An empty network namespace: unprivileged when the kernel allows it, else through sudo and back to this user.
    prefix = ["unshare", "-rn"]
    if subprocess.run(prefix + ["true"], capture_output=True).returncode != 0:
        prefix = ["sudo", "-n", "unshare", "-n", "setpriv", f"--reuid={os.getuid()}", f"--regid={os.getgid()}", "--init-groups"]
    e = env()
    e["FIRSTS_FILE"] = str(book)
    prefix += ["env", *[f"{k}={e[k]}" for k in ("HOME", "PATH", "FIRSTS_FILE", "NO_COLOR", "LC_ALL")]]
    links = subprocess.run(prefix + ["cat", "/proc/net/dev"], capture_output=True, text=True, env=e).stdout
    names = sorted(l.split(":")[0].strip() for l in links.split("\n")[2:] if ":" in l)
    log(f"$ {' '.join(prefix[:5])} ... cat /proc/net/dev   interfaces: {names}")
    check(names == ["lo"], "the namespace has only loopback")
    r = subprocess.run(prefix + ["uv", "run", "--offline", "firsts.py", "add", "swallow", "--date", "2025-04-02"],
                       cwd=ROOT, capture_output=True, text=True, env=e)
    log(f"$ {' '.join(prefix[:5])} ... uv run --offline firsts.py add swallow --date 2025-04-02   [exit {r.returncode}]",
        *[f"  | {l}" for l in (r.stdout + r.stderr).strip().split("\n")])
    check(r.returncode == 0 and r.stdout.startswith("Entered."), "runs with the network blocked")
    hook = ("import sys, runpy\n"
            "def no_net(event, args):\n"
            "    if event.startswith(('socket.', 'urllib.', 'http.')):\n"
            "        raise SystemExit('network call: ' + event)\n"
            "sys.addaudithook(no_net)\n"
            "sys.argv = ['firsts.py', 'table']\n"
            "runpy.run_path('firsts.py', run_name='__main__')\n")
    e = env()
    e["FIRSTS_FILE"] = str(book)
    r = subprocess.run(["uv", "run", "python", "-c", hook], cwd=ROOT, capture_output=True, text=True, env=e)
    check(r.returncode == 0 and "network call" not in r.stderr + r.stdout, "audit hook saw no socket, urllib or http event while printing a table")


def main():
    BIN.mkdir()
    (BIN / "firsts").symlink_to(ROOT / "firsts.py")
    log(f"today {T}, day {DOY}, year {Y}; books in a fresh temporary directory")
    log("", "CHECK 1: unit tests")
    r = subprocess.run(["uv", "run", "python", "-m", "unittest"], cwd=ROOT, capture_output=True, text=True, env=env())
    log(*[f"  | {l}" for l in r.stderr.strip().split("\n")[-3:]])
    check(r.returncode == 0, "uv run python -m unittest passes")
    book = check_2()
    check_4(book)
    filled = check_5()
    check_6(filled)
    check_7(filled)
    check_8_9()
    log("", "CHECK 3: append only, held on every command above")
    check(STATS["prefix"] > 0 and STATS["refused_unchanged"] > 0,
          f"{STATS['commands']} commands; {STATS['prefix']} on an existing file kept it as a prefix; {STATS['refused_unchanged']} refused left it identical")
    check_10()
    log("", "ALL CHECKS PASSED")
    (OUT / "e2e.log").write_text("\n".join(LOG) + "\n")


if __name__ == "__main__":
    main()
