"""Checks for Port of Entry: the hook in a real zsh, the counting rules, the passport HTML.

Run from this folder: uv run python -m unittest
Every log here is a synthetic fixture written to a temporary directory.
Chromium checks run only when a Chromium is found ($CHROME or the usual names).
"""

import html
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from datetime import date, timedelta
from pathlib import Path

import port

HERE = Path(__file__).resolve().parent
ONE = timedelta(days=1)
LONG_NAME = "resident-" + "r" * 69  # 78 characters
CJK_NAME = "\u6e2f\u53e3\u8a18\u9332\u7c3f\u5165\u56fd\u5be9\u67fb\u5c40\u5e33\u9762"  # 12 wide characters


def entry(day, root, clock="09:14:02"):
    return f"{day}T{clock}+0300\t{root}"


def span(first, last):
    days, day = [], first
    while day <= last:
        days.append(day)
        day += ONE
    return days


def write(path, lines):
    Path(path).write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
    return Path(path)


def reentry_log(path):
    """One root Resident on 2026-08-31 that lapses in September, plus two visitors."""
    days = span(date(2026, 3, 5), date(2026, 3, 31)) + span(date(2026, 6, 30), date(2026, 8, 31))
    lines = [entry(d, "/fixture/harbour") for d in days + [date(2026, 9, 20)]]
    lines += [entry(d, "/fixture/ledger") for d in (date(2026, 8, 3), date(2026, 8, 4), date(2026, 9, 2))]
    lines += [entry(d, "/fixture/quay", "18:40:11") for d in span(date(2026, 8, 10), date(2026, 8, 21))]
    return write(path, sorted(lines))


def thirteen_log(path):
    """Thirteen roots in 2026-09: one Resident with a 78-character name, long, wide and twin names."""
    names = [LONG_NAME, "ledger", "x" * 40, CJK_NAME, "a/notes", "b/notes", "archive", "atlas",
             "kiln", "orchard", "y" * 60, "signal", "tannery"]
    lines = [entry(d, f"/fixture/{LONG_NAME}") for d in span(date(2026, 6, 1), date(2026, 9, 30))]
    for i, name in enumerate(names[1:], 2):
        first = date(2026, 9, i)
        lines += [entry(first + k * 2 * ONE, f"/fixture/{name}", "10:0%d:00" % (k % 10)) for k in range(i)]
    return write(path, sorted(lines, key=lambda line: line[:19]))


def run_port(args, log, home=None, cwd=None):
    env = dict(os.environ, PORT_LOG=str(log))
    if home:
        env["HOME"] = str(home)
    return subprocess.run([sys.executable, str(HERE / "port.py"), *args], env=env, cwd=cwd,
                          capture_output=True, text=True)


def table(stdout):
    rows = {}
    for line in stdout.strip().split("\n")[1:]:
        root, days, first, last, status = re.split(r"\s{2,}", line.strip())
        rows[root] = (int(days), first, last, status)
    return rows


def sections(text):
    return re.findall(r'<section class="page[^"]*" id="([^"]+)">(.*?)</section>', text, re.S)


def cells(section):
    return [line for line in section.split("\n") if line.startswith('<div class="cell')]


def mrz(section):
    return [html.unescape(m) for m in re.search(r'<div class="mrz"><div>(.*?)</div><div>(.*?)</div></div>', section).groups()]


def strip_printed(text):
    return re.sub(r'<p class="printed">[^<]*</p>', "", text)


class Temp(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        self.addCleanup(shutil.rmtree, self.tmp, True)
        self.log = self.tmp / "log.tsv"
        self.out = self.tmp / "out"

    def pages(self, *args, log=None):
        result = run_port(["pages", *args, "--out", str(self.out)], log or self.log)
        self.assertEqual(result.returncode, 0, result.stderr)
        return Path(result.stdout.split("\n")[0]).read_text(encoding="utf-8")


class HookTest(Temp):
    def setUp(self):
        super().setUp()
        for name in ("A", "B"):
            (self.tmp / name / "sub" / "deeper").mkdir(parents=True)
            subprocess.run(["git", "init", "-q", str(self.tmp / name)], check=True)
        (self.tmp / "N").mkdir()
        (self.tmp / "home").mkdir()

    def zsh(self, script, cwd, **env):
        env = dict(os.environ, PORT_LOG=str(self.log), PORT_ZSH=str(HERE / "port.zsh"), HOME=str(self.tmp / "home"),
                   A=str(self.tmp / "A"), B=str(self.tmp / "B"), N=str(self.tmp / "N")) | env
        return subprocess.run(["zsh", "-f", "-c", script], cwd=cwd, env=env, capture_output=True, text=True)

    def logged(self):
        return self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else []

    def test_collapse(self):
        r = self.zsh('source $PORT_ZSH; cd $A; cd $A/sub/deeper; cd ..; cd $N; cd $B; cd $A', self.tmp / "N")
        self.assertEqual((r.stdout, r.stderr, r.returncode), ("", "", 0))
        lines = self.logged()
        self.assertEqual([line.split("\t")[1] for line in lines], [str(self.tmp / x) for x in "ABA"])
        for line in lines:
            self.assertRegex(line, r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\t/")
            self.assertNotIn("sub", line)

    def test_started_inside_repo(self):
        r = self.zsh('source $PORT_ZSH; print -r $PORT_HOME', self.tmp / "A")
        self.assertEqual(r.stdout.strip(), str(HERE))
        self.assertEqual([line.split("\t")[1] for line in self.logged()], [str(self.tmp / "A")])

    def test_home_repository_is_outside(self):
        home = self.tmp / "dot"
        (home / "x" / "y").mkdir(parents=True)
        (home / "other").mkdir()
        (home / ".git").mkdir()
        subprocess.run(["git", "init", "-q", str(home / "R")], check=True)
        r = self.zsh('source $PORT_ZSH; cd $HOME; cd $HOME/x; cd $HOME/x/y; cd $HOME', home, HOME=str(home))
        self.assertEqual((r.stdout, r.stderr, self.logged()), ("", "", []))
        r = self.zsh('source $PORT_ZSH; cd $HOME/R; cd $HOME/other; cd $HOME/R', home / "other", HOME=str(home))
        self.assertEqual((r.stdout, r.stderr), ("", ""))
        self.assertEqual([line.split("\t")[1] for line in self.logged()], [str(home / "R")] * 2)

    def test_tab_path_ignored(self):
        odd = self.tmp / "odd\tname"
        odd.mkdir()
        subprocess.run(["git", "init", "-q", str(odd)], check=True)
        r = self.zsh('source $PORT_ZSH; cd $ODD', self.tmp / "N", ODD=str(odd))
        self.assertEqual((r.stdout, r.stderr, self.logged()), ("", "", []))

    @unittest.skipIf(os.geteuid() == 0, "root can write anywhere")
    def test_unwritable_log(self):
        locked = self.tmp / "locked"
        locked.mkdir()
        locked.chmod(0o555)
        self.addCleanup(locked.chmod, 0o755)
        for log in (locked / "log.tsv", locked / "deeper" / "log.tsv"):
            r = self.zsh('source $PORT_ZSH; cd $A || exit 7', self.tmp / "N", PORT_LOG=str(log))
            self.assertEqual((r.stdout, r.stderr, r.returncode), ("", "", 0))
            self.assertFalse(log.exists())

    def test_user_options_do_not_reach_the_hook(self):
        o1, e1, o2, e2 = (self.tmp / n for n in ("o1", "e1", "o2", "e2"))
        script = ('setopt noclobber ksh_arrays nounset; source $PORT_ZSH; '
                  f'{{ cd $A }} >{o1} 2>{e1}; typeset -p ts dir root >{o2} 2>{e2}')
        self.assertFalse(self.log.exists())
        r = self.zsh(script, self.tmp / "N")
        self.assertEqual((r.stdout, r.stderr), ("", ""))
        self.assertEqual(len(self.logged()), 1)
        self.assertEqual((o1.read_text(), e1.read_text(), o2.read_text()), ("", "", ""))
        for name in ("ts", "dir", "root"):
            self.assertIn(f"no such variable: {name}", e2.read_text())

    def test_no_date_command(self):
        source = (HERE / "port.zsh").read_text()
        self.assertIn("zmodload zsh/datetime", source)
        self.assertNotRegex(source, r"\bdate\b")

    def test_thousand_cds_under_a_second(self):
        (self.tmp / "A" / "x").mkdir()
        (self.tmp / "A" / "y").mkdir()
        r = self.zsh('source $PORT_ZSH; cd $A/x; t=$EPOCHREALTIME; repeat 500 { cd $A/y; cd $A/x }; '
                     'print $(( EPOCHREALTIME - t ))', self.tmp / "N")
        seconds = float(r.stdout)
        print(f"\n1000 cd commands: {seconds:.4f} s", file=sys.stderr)
        self.assertEqual((r.stderr, len(self.logged())), ("", 1))
        self.assertLess(seconds, 1.0)


class RulesTest(Temp):
    ASOF = date(2026, 9, 30)

    def test_day_collapse(self):
        lines = [entry(date(2026, 9, 14), "/fixture/one", f"{h:02d}:{m:02d}:00") for h in range(10) for m in (0, 15, 30, 45)]
        write(self.log, lines)
        self.assertEqual(len(lines), 40)
        result = run_port(["list", "2026-09"], self.log)
        self.assertEqual(table(result.stdout)["/fixture/one"][0], 1)
        write(self.log, lines + [entry(date(2026, 9, 15), "/fixture/one"), entry(date(2026, 9, 20), "/fixture/one")])
        self.assertEqual(table(run_port(["list", "2026-09"], self.log).stdout)["/fixture/one"][0], 3)

    def test_89_then_90(self):
        days = [self.ASOF - 2 * k * ONE for k in range(1, 90)]
        self.assertEqual(port.window_status(sorted(days), self.ASOF), (89, None))
        write(self.log, [entry(d, "/fixture/one") for d in sorted(days)])
        status = table(run_port(["list", "2026-09"], self.log).stdout)["/fixture/one"][3]
        self.assertEqual(status, "visitor 89 of 90")
        days = sorted(days + [self.ASOF])
        self.assertEqual(port.window_count(days, self.ASOF - ONE), 89)
        write(self.log, [entry(d, "/fixture/one") for d in days])
        status = table(run_port(["list", "2026-09"], self.log).stdout)["/fixture/one"][3]
        self.assertEqual(status, "resident since 2026-09-30 (90 days in 180)")

    def test_resident_since_is_the_ninetieth_day(self):
        start = date(2026, 3, 15)
        days = span(start, start + 199 * ONE)
        asof = days[-1]
        since = port.resident_since(days, asof)
        self.assertEqual(since, start + 89 * ONE)
        self.assertNotEqual(since, asof - 89 * ONE)
        write(self.log, [entry(d, "/fixture/daily") for d in days])
        status = table(run_port(["list", f"{asof:%Y-%m}", "--as-of", str(asof)], self.log).stdout)["/fixture/daily"][3]
        self.assertEqual(status, f"resident since {start + 89 * ONE} (180 days in 180)")

    def test_window_edges_and_ageing_out(self):
        self.assertEqual(port.window_count([self.ASOF - 180 * ONE], self.ASOF), 0)
        self.assertEqual(port.window_count([self.ASOF - 179 * ONE], self.ASOF), 1)
        days = span(date(2026, 1, 1), date(2026, 3, 31))  # 90 days
        self.assertIsNotNone(port.window_status(days, date(2026, 3, 31))[1])
        self.assertIsNotNone(port.window_status(days, date(2026, 6, 29))[1])
        self.assertEqual(port.window_status(days, date(2026, 6, 30)), (89, None))
        self.assertEqual(port.window_status(days, date(2026, 12, 31)), (0, None))

    def test_reentry(self):
        reentry_log(self.log)
        august = self.pages("2026-08")
        box = [c for c in cells(august) if "harbour" in c][0]
        self.assertIn('class="cell resident"', box)
        self.assertIn("Resident since 2026-08-31", box)
        harbour = sorted({date.fromisoformat(line[:10]) for line in self.log.read_text().splitlines() if "harbour" in line})
        self.assertEqual(port.window_count(harbour, date(2026, 8, 30)), 89)
        september = self.pages("2026-09")
        stamp = [c for c in cells(september) if "HARBOUR" in c][0]
        self.assertIn(">RE-ENTRY<", stamp)
        self.assertIn(">DAY 64 OF 90<", stamp)
        ledger = [c for c in cells(september) if "LEDGER" in c][0]
        self.assertIn(">ENTRY<", ledger)
        self.assertNotIn("RE-ENTRY", ledger)


class PassportTest(Temp):
    def test_resident_data_stays_whole(self):
        reentry_log(self.log)
        rows = table(run_port(["list", "2026-08"], self.log).stdout)
        self.assertEqual(rows["/fixture/harbour"][:3], (31, "2026-03-05", "2026-08-31"))
        text = self.pages("2026-08")
        self.assertIn('<html data-theme="light"', text)
        boxes = cells(sections(text)[1][1])
        resident = [b for b in boxes if "harbour" in b][0]
        self.assertIn('class="cell resident"', resident)
        for fact in ("First entry 2026-03-05", "Days this month 31", "Last entry 2026-08-31",
                     "Days in 180 90", "Resident since 2026-08-31"):
            self.assertIn(f">{fact}<", resident)
        self.assertNotIn("<svg", resident)
        self.assertNotIn("transform", resident)
        for box in boxes:
            if "resident" in box or box == '<div class="cell"></div>':
                continue
            self.assertEqual(box.count("<svg"), 1)
            tilt = float(re.search(r"rotate\(([-\d.]+)\)", box).group(1))
            self.assertTrue(-6 <= tilt <= 6)
            root = "/fixture/" + re.findall(r"<text[^>]*>([^<]*)</text>", box)[1].lower()
            n = int(re.search(r">DAY (\d+) OF 90<", box).group(1))
            self.assertEqual(rows[root][3], f"visitor {n} of 90")

    def test_reprint_is_identical(self):
        reentry_log(self.log)
        first = self.pages("2026-09", "--as-of", "2026-09-30")
        second = self.pages("2026-09", "--as-of", "2026-09-30")
        self.assertEqual(first.count('<p class="printed">'), 1)
        self.assertEqual(strip_printed(first).encode(), strip_printed(second).encode())

    def test_seed_formulas(self):
        self.assertEqual([port.fnv1a(s) for s in ("", "a", "foobar")], [0x811C9DC5, 0xE40C292C, 0xBF9CF968])
        seed = port.seed_for("/srv/a", date(2026, 9, 1))
        self.assertEqual(seed, 0xAE3222EF)  # 2922521327: % 1201 = 721, >>8 % 41 = 17, >>16 % 41 = 27
        p = port.stamp_params(seed)
        self.assertEqual((round(p["tilt"], 2), p["dx"], p["dy"], p["shape"], p["ink"]), (1.21, -0.3, 0.7, "rect", "--c-moss"))
        seed = port.seed_for("/code/thing", date(2026, 10, 13))
        self.assertEqual(seed, 0x877F305B)  # 2273259611: % 1201 = 806, >>8 % 41 = 17, >>16 % 41 = 1
        p = port.stamp_params(seed)
        self.assertEqual((round(p["tilt"], 2), p["dx"], p["dy"], p["shape"], p["ink"]), (2.06, -0.3, -1.9, "rect", "--c-indigo"))
        later = port.stamp_params(port.seed_for("/code/thing", date(2026, 10, 14)))
        self.assertNotEqual(round(later["tilt"], 2), 2.06)

    def test_malformed_lines_are_shown(self):
        lines = thirteen_log(self.log).read_text().splitlines()
        self.assertGreater(len(lines), 41)
        clean = run_port(["list", "2026-09"], self.log).stdout
        write(self.log, lines[:40] + ["this is not an entry"] + lines[40:])
        self.assertEqual(run_port(["list", "2026-09"], self.log).stdout, clean)
        pages = sections(self.pages("2026-09"))
        self.assertIn("OBSERVATIONS", pages[-1][1])
        self.assertIn("Line 41 of the log could not be read and has not been counted.", pages[-1][1])

        def cover(text):
            c = sections(text)[0][1]
            return re.search(r'class="number">([0-9A-F]{8})<', c).group(1), re.search(r"Issued</dt><dd>([^<]+)<", c).group(1)
        write(self.log, lines)
        plain = cover(self.pages("2026-09"))
        write(self.log, ["garbage"] + lines)
        text = self.pages("2026-09")
        self.assertEqual(cover(text), plain)
        self.assertEqual(plain[1], "01 JUN 2026")
        self.assertIn("Line 1 of the log could not be read and has not been counted.", sections(text)[-1][1])

    def assert_refused(self, args, message, log=None, home=None):
        for command in ("list", "pages"):
            extra = ["--out", str(self.out)] if command == "pages" else []
            r = run_port([command, *args, *extra], log or self.log, home=home)
            self.assertEqual((r.returncode, r.stdout, r.stderr), (1, "", message + "\n"), (command, args))
            self.assertFalse(self.out.exists() and any(self.out.iterdir()))

    def test_refusals(self):
        empty = "No entries have been recorded. Source port.zsh to begin."
        write(self.log, [])
        self.assert_refused([], empty)
        self.assert_refused([], empty, log=self.tmp / "missing" / "log.tsv")
        if os.geteuid() != 0:
            home = self.tmp / "h"
            (home / "ro").mkdir(parents=True)
            (home / "ro").chmod(0o555)
            self.addCleanup((home / "ro").chmod, 0o755)
            self.assert_refused([], "The log at ~/ro/log.tsv cannot be written.", log=home / "ro" / "log.tsv", home=home)
        reentry_log(self.log)
        r = run_port(["list", "2026-02"], self.log)
        self.assertEqual((r.returncode, r.stdout), (1, ""))
        today = date.today()
        nxt = date(today.year + today.month // 12, today.month % 12 + 1, 1)
        self.assert_refused([f"{nxt:%Y-%m}"], f"The month {nxt:%Y-%m} has not begun.")
        self.assert_refused(["2026-09", "--as-of", "2026-08-31"], "The date 2026-08-31 is not in 2026-09.")
        self.assert_refused(["2026-09", "--as-of", "2026-10-01"], "The date 2026-10-01 is not in 2026-09.")
        for edge in ("2026-09-01", "2026-09-30"):
            self.assertEqual(run_port(["list", "2026-09", "--as-of", edge], self.log).returncode, 0)
            self.pages("2026-09", "--as-of", edge)

    def test_empty_month_page(self):
        reentry_log(self.log)
        text = self.pages("2026-05")
        pages = sections(text)
        self.assertEqual(len(pages), 2)
        self.assertIn("No entries were recorded in this period.", pages[1][1])
        self.assertEqual(cells(pages[1][1]), ['<div class="cell"></div>'] * 6)

    def test_only_the_resident_box_has_a_border(self):
        css = (HERE / "tokens.css").read_text() + port.CSS
        bordered = [sel.strip() for sel, body in re.findall(r"([^{}]+)\{([^{}]*)\}", css) if re.search(r"\bborder(-(top|right|bottom|left|width|style|color))?\s*:", body)]
        self.assertEqual(bordered, [".resident"])

    def test_mrz(self):
        self.assertEqual([port.check_digit(s) for s in ("L898902C3", "740812", "120415", "ZE184226B<<<<<")], list("6291"))
        thirteen_log(self.log)
        text = self.pages("2026-09")
        rows = table(run_port(["list", "2026-09"], self.log).stdout)
        for name, page in sections(text)[1:]:
            one, two = mrz(page)
            self.assertRegex(one, r"^[A-Z0-9<]{44}$")
            self.assertRegex(two, r"^[A-Z0-9<]{44}$")
            self.assertTrue(one.startswith("P<NID<<2026<09"))
            self.assertEqual(two[9], port.check_digit(two[:9]))
            self.assertEqual(two[43], port.check_digit(two[:43]))
            counts = [int(two[i:i + 3]) for i in range(10, 34, 4) if two[i:i + 3].isdigit()]
            expected = []
            for box in cells(page):
                n = re.search(r">DAY (\d+) OF 90<|>Days in 180 (\d+)<", box)
                if n:
                    expected.append(int(n.group(1) or n.group(2)))
            self.assertEqual(counts, expected)
        self.assertEqual(sum(len([c for c in cells(p) if c != '<div class="cell"></div>']) for _, p in sections(text)[1:]), len(rows))

    def test_offline_and_clean(self):
        thirteen_log(self.log)
        text = self.pages("2026-09")
        self.assertEqual(set(re.findall(r"https?://[^\s\"']+", text)), {"http://www.w3.org/2000/svg"})
        for name in ("port.zsh", "port.py"):
            self.assertEqual(re.findall(r"https?://", (HERE / name).read_text()), [])
        shipped = [p for p in HERE.rglob("*") if p.is_file() and p.suffix in {".zsh", ".py", ".css", ".svg", ".sh", ".md", ""}
                   and p.name not in {"CARD.md", "QA.md"} and not {"shots", "out", "__pycache__"} & set(p.parts)]
        bad = re.compile("[\u2013\u2014]| \x2d\x2d |[\U0001F000-\U0001FAFF\u2600-\u27BF]")
        home = str(Path.home())
        for path in shipped + [None]:
            body = text if path is None else path.read_text(encoding="utf-8")
            self.assertIsNone(bad.search(body), path)
            self.assertNotIn(home, body, path)


class StampFitTest(unittest.TestCase):
    FIXED = ["RE-ENTRY", None, "FIRST 2026-03-02", "31 DAYS THIS MONTH", "LAST 2026-10-13", "DAY 89 OF 90"]

    def lines(self, name):
        return [name if x is None else x for x in self.FIXED]

    def check_svg(self, svg):
        shape = re.search(r"<(rect|ellipse|circle) ", svg).group(1)
        tx, ty, tilt = map(float, re.search(r"translate\(([-\d.]+) ([-\d.]+)\) rotate\(([-\d.]+)\)", svg).groups())
        texts = re.findall(r'<text y="([-\d.]+)" textLength="([\d.]+)"[^>]*>([^<]*)</text>', svg)
        pitch = 3.0 if len(texts) == 6 else 2.6
        top = -len(texts) * pitch / 2
        a, b = port.INNER[shape]
        for y, length, text in texts:
            y, length = float(y), float(length)
            self.assertGreaterEqual(length / (port.natural_width(html.unescape(text)) * 1.32), 0.6 - 1e-3)
            i = math.floor((y - top) / pitch)
            edge = max(abs(top + i * pitch), abs(top + (i + 1) * pitch))
            self.assertLessEqual(edge, b)
            half = a if shape == "rect" else a * math.sqrt(1 - (edge / b) ** 2)
            self.assertLessEqual(length / 2, half, (shape, text))
        rad = math.radians(tilt)
        ox, oy = {"rect": (18, 11), "ellipse": (18, 11), "circle": (13, 13)}[shape]
        if shape == "rect":
            hw = ox * abs(math.cos(rad)) + oy * abs(math.sin(rad))
            hh = ox * abs(math.sin(rad)) + oy * abs(math.cos(rad))
        else:
            hw = math.hypot(ox * math.cos(rad), oy * math.sin(rad))
            hh = math.hypot(ox * math.sin(rad), oy * math.cos(rad))
        self.assertTrue(0 <= tx - hw and tx + hw <= 43 and 0 <= ty - hh and ty + hh <= 32, (shape, tx, ty, tilt))
        return shape, [html.unescape(t[2]) for t in texts]

    def stamp(self, name, shape):
        return self.check_svg(port.render_stamp(self.lines(name), shape, 6, 2, 2, "--c-brick"))

    def test_twelve_characters_keep_their_shape(self):
        for shape in port.STAMP_SHAPES:
            self.assertEqual(self.stamp("PORTOFENTRY1", shape)[0], shape)

    def test_wide_characters(self):
        self.assertEqual(port.natural_width(CJK_NAME), 24)
        self.assertEqual(self.stamp(CJK_NAME, "circle")[0], "rect")
        shape, _, _, scales = port.fit_lines(self.lines(CJK_NAME), "ellipse")
        self.assertEqual((shape, round(scales[1], 2)), ("ellipse", 0.79))
        self.assertEqual(self.stamp(CJK_NAME, "ellipse")[0], "ellipse")

    def test_long_names_wrap_in_the_rectangle(self):
        for width in (40, 60):
            root, k = None, 0
            while True:
                root = f"/fixture/{k}/" + "n" * width
                row = {"root": root, "first_in_month": date(2026, 9, 1), "first": date(2026, 3, 2), "last": date(2026, 9, 30),
                       "month": 31, "count": 89, "since": None, "reentry": True}
                if port.stamp_params(port.seed_for(root, row["first_in_month"]))["shape"] == "circle":
                    break
                k += 1
            shape, texts = self.check_svg(port.render_box(row, "n" * width))
            self.assertEqual(shape, "rect")
            self.assertEqual([len(t) for t in texts[1:3]], [width // 2] * 2)
            self.assertEqual(port.fit_lines(self.lines("N" * width), "circle")[2], 2.6)

    def test_boundaries(self):
        fit = lambda n, shape: port.fit_lines(self.lines("N" * n), shape)
        self.assertEqual((fit(23, "circle")[0], fit(24, "circle")[0]), ("circle", "rect"))
        self.assertEqual((fit(31, "ellipse")[0], fit(32, "ellipse")[0]), ("ellipse", "rect"))
        self.assertEqual((len(fit(39, "rect")[1]), len(fit(40, "rect")[1])), (6, 7))
        self.assertEqual(port.display_name("n" * 100), "..." + "n" * 75)
        cjk = (CJK_NAME * 4)[:39]
        shown = port.display_name(cjk)
        self.assertEqual((shown, port.natural_width(shown)), ("..." + cjk[-37:], 77))
        _, lines, _, _ = port.fit_lines(self.lines(shown), "circle")
        self.assertTrue(all(port.natural_width(x) <= 39 for x in lines[1:3]))
        for n in (12, 23, 24, 31, 32, 39, 40, 60, 78):
            for shape in port.STAMP_SHAPES:
                self.stamp("N" * n, shape)

    def test_resident_name_wrap(self):
        row = {"first": date(2026, 6, 1), "month": 30, "last": date(2026, 9, 30), "count": 122, "since": date(2026, 9, 2)}
        box = port.render_resident(row, port.display_name(LONG_NAME))
        self.assertEqual([len(x) for x in re.findall(r'class="line name">([^<]*)<', box)], [29, 29, 20])
        self.assertIn('<div class="line">Resident since 2026-09-02</div>', box)
        cjk = (CJK_NAME * 4)[:38]
        self.assertEqual([len(x) for x in port.wrap_name(cjk)], [14, 14, 10])
        self.assertTrue(all(port.natural_width(x) <= 29 for x in port.wrap_name(cjk)))


@unittest.skipUnless(port.find_chrome(), "no Chromium found")
class RenderTest(Temp):
    def render(self, page, *scheme):
        r = subprocess.run(["sh", str(HERE / "render.sh"), str(page), *scheme], capture_output=True, text=True)
        self.assertEqual(r.returncode, 0, r.stderr)
        return int(r.stdout)

    def test_page_count(self):
        thirteen_log(self.log)
        self.pages("2026-09")
        page = self.out / "passport-2026-09.html"
        self.assertEqual(self.render(page), 4)
        lines = self.log.read_text().splitlines()
        write(self.log, lines[:5] + ["unreadable"] + lines[5:])
        text = self.pages("2026-09")
        self.assertEqual(self.render(page), 5)
        last = sections(text)[-1][1]
        for part in ('class="kind">OBSERVATIONS<', "Page 4 of 4", 'class="mrz"', "Endorsements: none.", 'class="printed"'):
            self.assertIn(part, last)

    def test_dark_preference_cannot_reach_the_passport(self):
        source = (HERE / "render.sh").read_text()
        self.assertNotIn("WebContentsForceDark", source)
        self.assertEqual(re.findall(r"--[\w-]*(?:dark|color|colour|scheme)", source, re.I), [])
        style = "<style>body{background:#FFFFFF}@media (prefers-color-scheme: dark){body{background:#000000}}</style>"
        control = self.tmp / "control.html"
        control.write_text(f"<!doctype html><html><head>{style}</head><body></body></html>")
        twin = self.tmp / "twin.html"
        twin.write_text("<!doctype html><html><head><style>body{background:#000000}</style></head><body></body></html>")
        self.render(control)
        self.render(control, "dark")
        self.render(twin)
        shot = lambda name: (self.tmp / name).read_bytes()
        self.assertEqual(shot("control-dark.png"), shot("twin.png"))
        self.assertNotEqual(shot("control-dark.png"), shot("control.png"))
        reentry_log(self.log)
        self.pages("2026-08")
        page = self.out / "passport-2026-08.html"
        self.render(page)
        self.render(page, "dark")
        self.assertEqual((self.out / "passport-2026-08-dark.png").read_bytes(), (self.out / "passport-2026-08.png").read_bytes())


if __name__ == "__main__":
    unittest.main()
