"""Port of Entry: reads the log written by port.zsh, lists the month, prints the passport.

Python standard library only. Run through the `port` function of port.zsh, or
`uv run --no-project port.py list`.
"""

import argparse
import html
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unicodedata
from bisect import bisect_left, bisect_right
from calendar import monthrange
from datetime import date, datetime, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent
LIMIT, WINDOW = 90, 180
ONE = timedelta(days=1)
CHAR_MM = 0.6 * 2.2  # one character of natural width in the 2.2 mm monospace
TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}")
EMPTY = "No entries have been recorded. Source port.zsh to begin."
STAMP_SHAPES = ("rect", "circle", "ellipse")
STAMP_INKS = ("--c-brick", "--c-indigo", "--c-moss", "--c-copper")
INNER = {"rect": (16.8, 9.8), "ellipse": (16.8, 9.8), "circle": (11.8, 11.8)}
STAMP_RULES = {
    "rect": '<rect x="-17.7" y="-10.7" width="35.4" height="21.4" stroke-width=".6"/>'
    '<rect x="-16.8" y="-9.8" width="33.6" height="19.6" stroke-width=".25"/>',
    "ellipse": '<ellipse rx="17.7" ry="10.7" stroke-width=".6"/><ellipse rx="16.8" ry="9.8" stroke-width=".25"/>',
    "circle": '<circle r="12.7" stroke-width=".6"/><circle r="11.8" stroke-width=".25"/>',
}


# Log and counting rules


def well_formed(fields):
    if len(fields) != 2 or not fields[1].startswith("/") or not TIMESTAMP.fullmatch(fields[0]):
        return False
    try:
        datetime.strptime(fields[0], "%Y-%m-%dT%H:%M:%S%z")
    except ValueError:
        return False
    return True


def parse_log(text):
    """Return (entries, bad, first, count): (day, root) pairs, malformed line numbers,
    the first well-formed line, and the number of lines."""
    lines = text.split("\n")
    if lines and lines[-1] == "":
        lines.pop()
    entries, bad, first = [], [], None
    for n, line in enumerate(lines, 1):
        fields = line.split("\t")
        if not well_formed(fields):
            bad.append(n)
            continue
        entries.append((date.fromisoformat(fields[0][:10]), fields[1]))
        first = first or line
    return entries, bad, first, len(lines)


def days_by_root(entries, asof):
    """Distinct days per root, sorted, ignoring entries after the as-of date."""
    roots = {}
    for day, root in entries:
        if day <= asof:
            roots.setdefault(root, set()).add(day)
    return {root: sorted(days) for root, days in roots.items()}


def window_count(days, asof):
    """Distinct days in the 180 days ending on asof, inclusive."""
    return bisect_right(days, asof) - bisect_left(days, asof - (WINDOW - 1) * ONE)


def resident_since(days, asof):
    """Earliest D such that every date from D through asof has 90 or more days in its window."""
    since = asof
    while window_count(days, since - ONE) >= LIMIT:
        since -= ONE
    return since


def window_status(days, asof):
    """(days in the window, resident since or None)."""
    count = window_count(days, asof)
    return count, resident_since(days, asof) if count >= LIMIT else None


def month_rows(roots, start, asof):
    """One row per root with at least one day in the month up to asof."""
    rows = []
    for root, days in roots.items():
        in_month = days[bisect_left(days, start):]
        if not in_month:
            continue
        count, since = window_status(days, asof)
        rows.append({
            "root": root, "month": len(in_month), "first_in_month": in_month[0],
            "first": days[0], "last": days[-1], "count": count, "since": since,
            "reentry": since is None and window_count(days, start - ONE) >= LIMIT,
        })
    return rows


def status(row):
    if row["since"]:
        return f"resident since {row['since']} ({row['count']} days in {WINDOW})"
    return f"visitor {row['count']} of {LIMIT}"


# Names and widths


def natural_width(text):
    return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in text)


def display_name(name):
    """Cap at a natural width of 78, or 77 with a wide character: '...' plus the longest tail that fits."""
    cap = 77 if natural_width(name) != len(name) else 78
    if natural_width(name) <= cap:
        return name
    tail, width = "", 0
    for c in reversed(name):
        if width + natural_width(c) > cap - 3:
            break
        tail, width = c + tail, width + natural_width(c)
    return "..." + tail


def wrap_name(name, width=29):
    """Split by character at a natural width; a wide character that would pass it moves down."""
    lines, line, used = [], "", 0
    for c in name:
        if used + natural_width(c) > width:
            lines.append(line)
            line, used = "", 0
        line, used = line + c, used + natural_width(c)
    return lines + [line] if line else lines


def folder_labels(roots):
    """Folder names, with parent/name for roots on the same page that share one."""
    names = [os.path.basename(r) or r for r in roots]
    return [
        f"{os.path.basename(os.path.dirname(r))}/{n}" if names.count(n) > 1 else n
        for r, n in zip(roots, names)
    ]


# Stamps


def fnv1a(text):
    h = 0x811C9DC5
    for b in text.encode("utf-8"):
        h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF
    return h


def seed_for(root, first_day_in_month):
    return fnv1a(f"{root}|{first_day_in_month.isoformat()}")


def stamp_params(seed):
    return {
        "tilt": -6 + (seed % 1201) / 100,
        "dx": (((seed >> 8) % 41) - 20) / 10,
        "dy": (((seed >> 16) % 41) - 20) / 10,
        "shape": STAMP_SHAPES[(seed >> 24) % 3],
        "ink": STAMP_INKS[(seed >> 4) % 4],
    }


def usable_width(shape, edge):
    """Room for a line whose slot reaches `edge` mm from the stamp's centre."""
    if shape == "rect":
        return 33.6 - 2
    a, b = INNER[shape]
    return 2 * a * math.sqrt(1 - (edge / b) ** 2) - 1.5


def line_edges(count, pitch):
    top = -count * pitch / 2
    return [max(abs(top + i * pitch), abs(top + (i + 1) * pitch)) for i in range(count)]


def fit_lines(lines, shape):
    """Return (shape, lines, pitch, scales). The name is line 2; it may force the rectangle,
    then a split onto two lines at a 2.6 mm pitch."""
    name = lines[1]
    need = max(natural_width(name), 1) * CHAR_MM
    if shape != "rect" and usable_width(shape, 6) / need < 0.6:
        shape = "rect"
    pitch = 3.0
    if usable_width(shape, 6) / need < 0.6:
        half, cut, used = math.ceil(natural_width(name) / 2), 0, 0
        while used + natural_width(name[cut]) <= half:
            used += natural_width(name[cut])
            cut += 1
        lines = [lines[0], name[:cut], name[cut:], *lines[2:]]
        pitch = 2.6
    edges = line_edges(len(lines), pitch)
    scales = [min(1.0, usable_width(shape, e) / (max(natural_width(t), 1) * CHAR_MM)) for t, e in zip(lines, edges)]
    return shape, list(lines), pitch, scales


def render_stamp(lines, shape, tilt, dx, dy, ink):
    shape, lines, pitch, scales = fit_lines(lines, shape)
    top = -len(lines) * pitch / 2
    texts = []
    for i, (text, scale) in enumerate(zip(lines, scales)):
        y = top + (i + 0.5) * pitch + 0.8
        length = natural_width(text) * CHAR_MM * scale
        bold = ' font-weight="700"' if i < len(lines) - 4 else ""  # ENTRY and the name
        texts.append(
            f'<text y="{y:.2f}" textLength="{length:.3f}" lengthAdjust="spacingAndGlyphs"{bold}>'
            f"{html.escape(text)}</text>"
        )
    return (
        '<svg class="stamp" viewBox="0 0 43 32" width="43mm" height="32mm">'
        f'<g transform="translate({21.5 + dx:.2f} {16 + dy:.2f}) rotate({tilt:.2f})" style="color:var({ink})">'
        f'<g fill="none" stroke="currentColor">{STAMP_RULES[shape]}</g>'
        f'<g fill="currentColor" font-size="2.2" text-anchor="middle">{"".join(texts)}</g>'
        "</g></svg>"
    )


def render_resident(row, name):
    lines = ['<div class="line"><b>Resident</b></div>']
    lines += [f'<div class="line name">{html.escape(part)}</div>' for part in wrap_name(name)]
    facts = (
        ("First entry", row["first"]), ("Days this month", row["month"]), ("Last entry", row["last"]),
        (f"Days in {WINDOW}", row["count"]), ("Resident since", row["since"]),
    )
    lines += [f'<div class="line">{label} {value}</div>' for label, value in facts]
    return f'<div class="cell resident">{"".join(lines)}</div>'


# Machine-readable zone


def check_digit(text):
    """ICAO Doc 9303: values times the weights 7, 3, 1, modulo 10."""
    total = 0
    for i, c in enumerate(text):
        value = 0 if c == "<" else int(c) if c.isdigit() else ord(c) - ord("A") + 10
        total += value * (7, 3, 1)[i % 3]
    return str(total % 10)


def render_mrz(number, start, counts):
    first = f"P<NID<<{start.year}<{start.month:02d}".ljust(44, "<")
    second = number + "<"
    second += check_digit(second) + "".join(f"{c:03d}<" for c in counts)
    second = second.ljust(43, "<")
    return first, second + check_digit(second)


# Pages

RULING = "".join(f"M0 {y}H105" for y in range(1, 148))


def ruling():
    return f'<svg class="ruling" viewBox="0 0 105 148" aria-hidden="true"><path d="{RULING}"/></svg>'


def render_box(row, label):
    if row["since"]:
        return render_resident(row, display_name(label))
    days = row["month"]
    lines = [
        "RE-ENTRY" if row["reentry"] else "ENTRY",
        display_name(label.upper()),
        f"FIRST {row['first']}",
        f"{days} DAY{'S' if days != 1 else ''} THIS MONTH",
        f"LAST {row['last']}",
        f"DAY {row['count']} OF {LIMIT}",
    ]
    p = stamp_params(seed_for(row["root"], row["first_in_month"]))
    return f'<div class="cell">{render_stamp(lines, p["shape"], p["tilt"], p["dx"], p["dy"], p["ink"])}</div>'


def render_page(title, n, total, start, body, counts, number, printed):
    mrz = "".join(f"<div>{html.escape(line)}</div>" for line in render_mrz(number, start, counts))
    month = f"{start:%b %Y}".upper()
    return (
        f'<section class="page" id="p{n}">\n{ruling()}\n'
        f'<header class="head"><span class="kind">{title}</span>'
        f'<span class="month">{month}</span><span class="pageno">Page {n} of {total}</span></header>\n'
        f"{body}\n"
        f'<div class="mrz">{mrz}</div>\n'
        f'<footer class="foot"><p>Endorsements: none.</p><p class="printed">{printed}</p></footer>\n'
        "</section>"
    )


def render_visa(boxes):
    labels = folder_labels([b["root"] for b in boxes])
    cells = [render_box(b, label) for b, label in zip(boxes, labels)]
    cells += ['<div class="cell"></div>'] * (6 - len(cells))
    note = "" if boxes else '<p class="note">No entries were recorded in this period.</p>\n'
    return note + '<div class="grid">\n' + "\n".join(cells) + "\n</div>"


def render_observations(bad):
    lines = [f"<p>Line {n} of the log could not be read and has not been counted.</p>" for n in bad[:5]]
    rest = len(bad) - 5
    if rest == 1:
        lines.append("<p>1 more line could not be read and has not been counted.</p>")
    elif rest > 1:
        lines.append(f"<p>{rest} more lines could not be read and have not been counted.</p>")
    return '<div class="obs">' + "".join(lines) + "</div>"


def render_cover(number, issued, authority):
    wordmark = (HERE / "wordmark.svg").read_text(encoding="utf-8").strip()
    fields = (
        ("", "Passport No.", f'<span class="number">{number}</span>'),
        ("", "Issued", f"{issued:%d %b %Y}".upper()),
        (' class="wide"', "Territory", "git repositories"),
        (' class="wide"', "Issuing authority", html.escape(authority)),
        (' class="wide"', "Holder", "the user of this shell"),
    )
    rows = "".join(f"<div{cls}><dt>{label}</dt><dd>{value}</dd></div>" for cls, label, value in fields)
    return (
        f'<section class="page cover" id="cover">\n{ruling()}\n'
        '<h1 class="title">PASSPORT</h1>\n'
        f'<dl class="fields">{rows}</dl>\n'
        '<div class="conditions"><p class="label">Conditions of stay</p>'
        f"<p>A holder who enters a territory on {LIMIT} days within any period of {WINDOW} days "
        "is recorded as Resident. Residents are no longer stamped.</p></div>\n"
        f'<div class="mark">{wordmark}</div>\n'
        "</section>"
    )


def render_passport(log_path, first_line, start, rows, bad, line_count, printed_at):
    number = f"{fnv1a(first_line):08X}"
    issued = date.fromisoformat(first_line[:10])
    rows = sorted(rows, key=lambda r: (r["first_in_month"], r["root"]))
    chunks = [rows[i:i + 6] for i in range(0, len(rows), 6)] or [[]]
    total = len(chunks) + (1 if bad else 0)
    printed = f"Printed {printed_at:%d %b %Y %H:%M}. Log: {line_count} line{'s' if line_count != 1 else ''}."
    pages = [render_cover(number, issued, tilde(log_path))]
    for n, boxes in enumerate(chunks, 1):
        pages.append(render_page("VISAS", n, total, start, render_visa(boxes), [b["count"] for b in boxes], number, printed))
    if bad:
        pages.append(render_page("OBSERVATIONS", total, total, start, render_observations(bad), [], number, printed))
    tokens = (HERE / "tokens.css").read_text(encoding="utf-8")
    return (
        '<!doctype html>\n<html data-theme="light" lang="en">\n<head>\n<meta charset="utf-8">\n'
        '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
        f"<title>Passport {start:%Y-%m}</title>\n<style>\n{tokens}</style>\n<style>{CSS}</style>\n</head>\n<body>\n"
        + "\n".join(pages)
        + "\n</body>\n</html>\n"
    )


CSS = """
:root { --mono: ui-monospace, "SF Mono", Menlo, Consolas, "DejaVu Sans Mono", "Liberation Mono", monospace;
  --desk: color-mix(in srgb, var(--c-teal) 34%, var(--c-cream)); color-scheme: light; }
@page { size: 105mm 148mm; margin: 0; }
html { color-scheme: light; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
html, body { margin: 0; padding: 0; }
body { background: var(--desk); color: var(--ink); font-family: var(--font-body); }
p, h1, dl, dd { margin: 0; }
.page { position: relative; flex: none; width: 105mm; height: 148mm; overflow: hidden; background: var(--c-cream);
  break-after: page; break-inside: avoid; }
.ruling { position: absolute; left: 0; top: 0; width: 105mm; height: 148mm; }
.ruling path { stroke: var(--c-teal); stroke-width: .05; opacity: .45; }
.head { position: absolute; left: 8mm; right: 8mm; top: 8mm; display: grid; grid-template-columns: 1fr auto 1fr;
  align-items: baseline; }
.kind { font-size: 2.8mm; font-weight: 700; letter-spacing: .22em; color: var(--c-earth); }
.month { font-family: var(--mono); font-size: 2.6mm; }
.pageno { font-size: 2mm; letter-spacing: .14em; text-transform: uppercase; text-align: right; }
.note { position: absolute; left: 8mm; top: 13.6mm; font-size: 2.3mm; }
.grid { position: absolute; left: 8mm; top: 17mm; display: grid; grid-template-columns: 43mm 43mm;
  grid-template-rows: 32mm 32mm 32mm; column-gap: 3mm; row-gap: 2mm; }
.cell { box-sizing: border-box; width: 43mm; height: 32mm; }
.stamp { display: block; width: 43mm; height: 32mm; overflow: visible; font-family: var(--mono); }
.resident { border: .5mm solid var(--ink); padding: 1.5mm; background: var(--c-cream); color: var(--ink);
  font-family: var(--mono); font-size: 2.2mm; line-height: 3.1mm; }
.resident .line { height: 3.1mm; white-space: pre; }
.mrz { position: absolute; left: 8mm; top: 121mm; font-family: var(--mono); font-size: 3.3mm;
  line-height: 4.4mm; white-space: pre; letter-spacing: 0; }
.foot { position: absolute; left: 8mm; right: 8mm; top: 131.5mm; font-size: 2mm; line-height: 3mm; }
.obs { position: absolute; left: 8mm; right: 8mm; top: 17mm; font-size: 2.8mm; line-height: 4.2mm; }
.obs p + p { margin-top: 2mm; }
.cover .title { position: absolute; left: 0; right: 0; top: 17mm; text-align: center; font-size: 7mm;
  line-height: 1; font-weight: 700; letter-spacing: .32em; text-indent: .32em; color: var(--c-earth); }
.fields { position: absolute; left: 12mm; right: 12mm; top: 36mm; display: grid;
  grid-template-columns: 1fr 1fr; gap: 4.2mm 4mm; }
.fields .wide { grid-column: span 2; }
.fields dt, .conditions .label { font-size: 1.9mm; letter-spacing: .16em; text-transform: uppercase; }
.fields dd { margin-top: .9mm; font-family: var(--mono); font-size: 3.1mm; line-height: 1.3;
  overflow-wrap: anywhere; }
.number { color: var(--c-earth); }
.conditions { position: absolute; left: 12mm; right: 12mm; top: 93mm; font-size: 2.9mm; line-height: 4.3mm; }
.conditions .label { margin-bottom: 1.2mm; line-height: 1; }
.mark { position: absolute; left: 0; right: 0; bottom: 9mm; text-align: center; }
.mark svg { width: 27mm; height: auto; }
@media screen {
  body { display: flex; flex-wrap: wrap; justify-content: center; align-items: flex-start; gap: 32px;
    padding: 32px 16px; }
  body:has(.page:target) { display: block; padding: 0; }
  body:has(.page:target) .page { margin: 0 auto; }
  body:has(.page:target) .page:not(:target) { display: none; }
}
@media screen and (min-width: 900px) { .page { zoom: 1.4; } }
@media screen and (max-width: 440px) { .page { zoom: .9; } body { gap: 16px; padding: 16px 0; } }
@media screen and (min-width: 397px) and (max-width: 440px) { body:has(.page:target) .page { zoom: 1; } }
"""


# Command line


def tilde(path):
    home, path = os.path.expanduser("~").rstrip("/"), str(path)
    return "~" + path[len(home):] if home and (path == home or path.startswith(home + "/")) else path


def log_path():
    if os.environ.get("PORT_LOG"):
        return Path(os.environ["PORT_LOG"])
    data = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")
    return Path(data) / "port" / "log.tsv"


def writable(directory):
    while not directory.exists() and directory != directory.parent:
        directory = directory.parent
    return os.access(directory, os.W_OK)


def read_log(path):
    if not path.exists():
        sys.exit(EMPTY if writable(path.parent) else f"The log at {tilde(path)} cannot be written.")
    try:
        text = path.read_bytes().decode("utf-8", "replace")
    except OSError:
        sys.exit(f"The log at {tilde(path)} cannot be read.")
    entries, bad, first, count = parse_log(text)
    if first is None:
        sys.exit(EMPTY)
    return entries, bad, first, count


def resolve_dates(month, as_of, today):
    start = month or today.replace(day=1)
    end = start.replace(day=monthrange(start.year, start.month)[1])
    if start > today:
        sys.exit(f"The month {start:%Y-%m} has not begun.")
    if as_of and not start <= as_of <= end:
        sys.exit(f"The date {as_of} is not in {start:%Y-%m}.")
    return start, as_of or min(end, today)


def format_table(rows):
    rows = sorted(rows, key=lambda r: (-r["month"], -r["last"].toordinal(), r["root"]))
    table = [("ROOT", "DAYS", "FIRST", "LAST", "STATUS")]
    table += [(tilde(r["root"]), str(r["month"]), str(r["first"]), str(r["last"]), status(r)) for r in rows]
    w = [max(natural_width(t[i]) for t in table) for i in range(4)]
    return "\n".join(
        f"{t[0]}{' ' * (w[0] - natural_width(t[0]))}  {t[1]:>{w[1]}}  {t[2]:<{w[2]}}  {t[3]:<{w[3]}}  {t[4]}"
        for t in table
    )


def find_chrome():
    if os.environ.get("CHROME"):
        return os.environ["CHROME"]
    for name in ("chromium", "chromium-browser", "google-chrome"):
        if shutil.which(name):
            return shutil.which(name)
    mac = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    return mac if os.path.exists(mac) else None


def print_pdf(page):
    chrome = find_chrome()
    if not chrome:
        sys.exit("No Chromium was found, so no PDF was written.")
    pdf = page.with_suffix(".pdf")
    pdf.unlink(missing_ok=True)
    with tempfile.TemporaryDirectory() as profile:
        try:
            subprocess.run(
                [chrome, "--headless", "--disable-gpu", f"--user-data-dir={profile}", "--no-pdf-header-footer",
                 f"--print-to-pdf={pdf}", page.resolve().as_uri()],
                stdin=subprocess.DEVNULL, capture_output=True, timeout=120,
            )
        except (OSError, subprocess.TimeoutExpired):
            pass
    if not pdf.exists() or pdf.stat().st_size == 0:
        sys.exit("Chromium did not write the PDF.")
    return pdf


def month_arg(text):
    if not re.fullmatch(r"\d{4}-\d{2}", text) or not 1 <= int(text[5:]) <= 12:
        raise argparse.ArgumentTypeError(f"{text} is not a month (YYYY-MM)")
    return date(int(text[:4]), int(text[5:]), 1)


def date_arg(text):
    if re.fullmatch(r"\d{4}-\d{2}-\d{2}", text):
        try:
            return date.fromisoformat(text)
        except ValueError:
            pass
    raise argparse.ArgumentTypeError(f"{text} is not a date (YYYY-MM-DD)")


def main(argv=None):
    parser = argparse.ArgumentParser(prog="port", description="Where you really worked, by day.")
    commands = parser.add_subparsers(dest="command", required=True)
    for name in ("list", "pages"):
        command = commands.add_parser(name)
        command.add_argument("month", nargs="?", type=month_arg, help="YYYY-MM, default the current month")
        command.add_argument("--as-of", type=date_arg, help="YYYY-MM-DD inside the month")
        if name == "pages":
            command.add_argument("--out", default=".", help="directory for the passport, default here")
            command.add_argument("--pdf", action="store_true", help="also print the PDF with headless Chromium")
    args = parser.parse_args(argv)

    start, asof = resolve_dates(args.month, args.as_of, date.today())
    path = log_path()
    entries, bad, first, count = read_log(path)
    issued = date.fromisoformat(first[:10])
    if start < issued.replace(day=1):
        sys.exit(f"The month {start:%Y-%m} is before the passport was issued, on {issued}.")
    rows = month_rows(days_by_root(entries, asof), start, asof)

    if args.command == "list":
        print(format_table(rows) if rows else "No entries were recorded in this period.")
        return 0
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    page = out / f"passport-{start:%Y-%m}.html"
    page.write_text(render_passport(path, first, start, rows, bad, count, datetime.now()), encoding="utf-8")
    print(page)
    if args.pdf:
        print(print_pdf(page))
    return 0


if __name__ == "__main__":
    sys.exit(main())
