#!/usr/bin/env -S uv run --script
"""First occurrences: a register of the first time each year something happens."""

import argparse
import os
import re
import shutil
import string
import sys
from datetime import date
from pathlib import Path
from typing import NamedTuple

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."
OPENED = re.compile(r"# Opened ([0-9]{4}-[0-9]{2}-[0-9]{2})\.")
ISO = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
BRICK, PLAIN = "\x1b[38;2;236;94;82m", "\x1b[39m"
LABEL_MAX = 22


class Entry(NamedTuple):
    date: date
    basis: str
    event: str
    note: str
    line: int


class Erratum(NamedTuple):
    year: int
    event: str
    filed: date
    text: str
    line: int


class Book(NamedTuple):
    entries: list
    errata: list
    opened: date | None
    problems: list


def today():
    return date.today()


def command_name(argv0):
    name = Path(argv0).name
    return f"uv run {name}" if name.endswith(".py") else name


def one_line(text):
    return " ".join(text.split())


def normalise(name):
    name = one_line(name.lower()).rstrip(string.punctuation).strip()
    return name[len("first "):] if name.startswith("first ") else name


def fold(name):
    return name[:-1] if name.endswith("s") else name


def iso_date(text):
    """A date written exactly YYYY-MM-DD, or None."""
    if not ISO.fullmatch(text):
        return None
    try:
        return date.fromisoformat(text)
    except ValueError:
        return None


def doy(d):
    return d.timetuple().tm_yday


def fmt_date(d, year=True):
    day = f"{d.day} {MONTHS[d.month - 1]}"
    return f"{day} {d.year}" if year else day


def plural(n, word):
    return f"{n} {word}" if n == 1 else f"{n} {word}s"


def parse_entry(line, number):
    fields = [f.strip() for f in line.split("|", 3)]
    if len(fields) < 3:
        return None
    when, basis, event = iso_date(fields[0]), fields[1].lower(), normalise(fields[2])
    if not when or basis not in ("seen", "recalled") or not event:
        return None
    return Entry(when, basis, event, fields[3] if len(fields) == 4 else "", number)


def parse_erratum(line, number):
    fields = [f.strip() for f in line.split("|", 4)]
    if len(fields) != 5 or fields[0] != "erratum" or not re.fullmatch(r"[0-9]{4}", fields[1]):
        return None
    filed = iso_date(fields[3][len("filed "):]) if fields[3].startswith("filed ") else None
    event = normalise(fields[2])
    if not filed or not event:
        return None
    return Erratum(int(fields[1]), event, filed, fields[4], number)


def parse(text):
    """Read the book leniently. Returns a Book; never touches a file."""
    entries, errata, opened, problems, first = [], [], None, [], {}
    for number, raw in enumerate(text.split("\n"), 1):
        line = raw.rstrip("\r").strip()
        if not line or line.startswith("#"):
            match = OPENED.fullmatch(line)
            if match and opened is None:
                opened = iso_date(match.group(1))
            continue
        item = parse_entry(line, number) or parse_erratum(line, number)
        if item is None:
            problems.append((number, "is not an entry. Left as it is."))
        elif isinstance(item, Erratum):
            errata.append(item)
        else:
            key = (fold(item.event), item.date.year)
            if key in first:
                problems.append((number, f"repeats {first[key].event} {item.date.year}. The first line stands."))
            else:
                first[key] = item
                entries.append(item)
    return Book(entries, errata, opened, problems)


def refusals(entries, new):
    """Problems for a batch of new entries: (index, message, existing entry or None)."""
    found = []
    held = {(fold(e.event), e.date.year): e for e in entries}
    batch = {}
    for i, e in enumerate(new):
        key = (fold(e.event), e.date.year)
        if not e.event or "|" in e.event:
            found.append((i, "An event needs a name, without |.", None))
        elif e.date > today():
            found.append((i, f"{fmt_date(e.date)} has not happened.", None))
        elif key in held:
            old = held[key]
            found.append((i, f"{old.event}, {old.date.year}: already entered, {fmt_date(old.date, False)}. The first is final.", old))
        elif key in batch:
            found.append((i, f"{e.event}, {e.date.year}: also given on line {batch[key].line}.", None))
        else:
            batch[key] = e
    return found


def split_erratum(words, cmd="firsts"):
    """Event words, a four-digit year, then text. Returns (event, year, text) or the usage line."""
    usage = f"Usage: {cmd} erratum EVENT... YEAR TEXT..."
    at = next((i for i, w in enumerate(words) if re.fullmatch(r"[0-9]{4}", w)), None)
    if at is None or at == 0 or at == len(words) - 1:
        return usage
    event, text = normalise(" ".join(words[:at])), one_line(" ".join(words[at + 1:]))
    return (event, int(words[at]), text) if event and text else usage


def label(name):
    return name if len(name) <= LABEL_MAX else name[:LABEL_MAX - 1] + "~"


def names_of(book):
    """Display name per folded event: the spelling entered first."""
    names = {}
    for e in book.entries:
        names.setdefault(fold(e.event), e.event)
    return names


def rows_for(book, years):
    """Shown rows in calendar order: (display name, {year: entry})."""
    groups, names = {}, names_of(book)
    for e in book.entries:
        groups.setdefault(fold(e.event), {})[e.date.year] = e
    rows = []
    for key, cells in groups.items():
        if any(y in cells for y in years):
            latest = cells[max(cells)]
            rows.append((doy(latest.date), names[key], cells))
    return [(name, cells) for _, name, cells in sorted(rows, key=lambda r: (r[0], r[1]))]


def render_table(book, from_year=None, days=False, width=80, cmd="firsts", colour=False):
    """The table, the lines under it and the colophon, as one string."""
    def paint(s):
        return f"{BRICK}{s}{PLAIN}" if colour else s

    marked = {(fold(x.event), x.year) for x in book.errata}
    oldest = min(e.date.year for e in book.entries)
    newest = max(e.date.year for e in book.entries)
    years = list(range(max(from_year or oldest, oldest), newest + 1))
    while True:
        rows = rows_for(book, years)
        pad = max(len(label(name)) for name, _ in rows) + 2
        if from_year is not None or len(years) == 1 or pad + 9 * len(years) <= width:
            break
        years = years[1:]

    seen_marks, shown = set(), []
    lines = [(" " * pad + "".join(f" {y}".ljust(9) for y in years)).rstrip()]
    for name, cells in rows:
        out = label(name).ljust(pad)
        for y in years:
            e = cells.get(y)
            if e is None:
                out += " " * 9
                continue
            body = f"{doy(e.date):>6}" if days else f"{MONTHS[e.date.month - 1]} {e.date.day:>2}"
            star = (fold(e.event), y) in marked
            mark = paint("[") if e.basis == "recalled" else " "
            end = paint("]") if e.basis == "recalled" else " "
            out += mark + body + end + (paint("*") if star else " ")
            seen_marks.update({"recalled"} if e.basis == "recalled" else set())
            seen_marks.update({"erratum"} if star else set())
            shown.append((name, e))
        lines.append(out.rstrip())

    lines.append("")
    if years[0] > oldest and from_year is None:
        lines.append(f"Years before {years[0]} not shown. {cmd} table --from {oldest}.")
    key = [paint("[ ]") + " recalled"] if "recalled" in seen_marks else []
    key += [paint("*") + " erratum"] if "erratum" in seen_marks else []
    key += ["Day counts from 1 Jan."] if days else []
    if key:
        lines.append("   ".join(key))
    for name, e in shown:
        for x in book.errata:
            if (fold(x.event), x.year) == (fold(e.event), e.date.year):
                filed = fmt_date(x.filed, x.filed.year != x.year)
                lines.append(paint(f"* {name} {x.year}, filed {filed}: {x.text}"))
    now = today().year
    this_year = {fold(e.event) for e in book.entries if e.date.year == now}
    names = names_of(book)
    waiting = sorted({names[fold(e.event)] for e in book.entries if e.date.year < now} - {names[k] for k in this_year})
    if waiting:
        lines.append(f"Not yet in {now}: {', '.join(waiting)}.")
    lines.append(colophon(book))
    return "\n".join(lines)


def colophon(book):
    count = "1 entry" if len(book.entries) == 1 else f"{len(book.entries)} entries"
    tail = "This tool has changed no line."
    if book.opened is None:
        return f"{count}. {tail}"
    older = sum(e.date < book.opened for e in book.entries)
    return f"Book opened {fmt_date(book.opened)}. {count}, {older} of them older than the book. {tail}"


def entry_line(e):
    note = f" | {e.note}" if e.note else ""
    return f"{e.date.isoformat()} | {e.basis} | {e.event}{note}"


def compare(book, new, paint):
    """One line per earlier year of the same event, newest first."""
    earlier = sorted((e for e in book.entries if fold(e.event) == fold(new.event) and e.date.year < new.date.year),
                     key=lambda e: e.date.year, reverse=True)
    out = []
    for e in earlier:
        shown = fmt_date(e.date, False)
        shown = paint("[") + shown + paint("]") if e.basis == "recalled" else shown
        gap = doy(new.date) - doy(e.date)
        how = "on the same day" if gap == 0 else plural(abs(gap), "day") + (" earlier" if gap < 0 else " later")
        out.append(f"{e.date.year}: {shown} (day {doy(e.date)}). This entry is {how}.")
    return out


def date_arg(text):
    d = iso_date(text)
    if d is None:
        raise argparse.ArgumentTypeError(f"{text} is not a date written YYYY-MM-DD")
    return d


def build_parser(cmd):
    p = argparse.ArgumentParser(
        prog=cmd,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="A register of first occurrences, printed one column per year.\n"
                    "Kept in $FIRSTS_FILE, or ~/firsts.txt when that is not set.\n"
                    f"With no command, prints the table ({cmd} table).",
        epilog="The file is yours. This tool only adds to it.\nnormal is dead",
    )
    sub = p.add_subparsers(dest="command", title="commands", metavar="{add,backfill,erratum,table}")
    a = sub.add_parser("add", help="enter the first time something happened this year")
    a.add_argument("event", nargs="+", metavar="EVENT")
    a.add_argument("--date", type=date_arg, help="YYYY-MM-DD, default today")
    a.add_argument("--recalled", action="store_true", help="from memory, not seen today (needs --date)")
    a.add_argument("--note", nargs="+", default=[], metavar="TEXT", help="words kept with the entry")
    b = sub.add_parser("backfill", help="paste earlier years, one YYYY-MM-DD event per line")
    b.add_argument("--seen", action="store_true", help="store the lines as seen, not recalled")
    e = sub.add_parser("erratum", help="note a correction: EVENT... YEAR TEXT...")
    e.add_argument("words", nargs=argparse.REMAINDER)
    t = sub.add_parser("table", help="print the table")
    t.add_argument("--from", dest="from_year", type=int, metavar="YEAR", help="show every year from YEAR on")
    t.add_argument("--days", action="store_true", help="day of the year instead of the date")
    return p


def read_paste(lines, basis):
    """Backfill lines into entries, or (line number, problem) pairs."""
    entries, bad = [], []
    for number, raw in enumerate(lines, 1):
        line = raw.strip()
        if not line:
            continue
        head, _, rest = line.partition(" ")
        event, _, note = rest.partition("|")
        when = iso_date(head)
        if when is None or not normalise(event):
            bad.append((number, "is not YYYY-MM-DD event."))
            continue
        entries.append(Entry(when, basis, normalise(event), one_line(note), number))
    return entries, bad


def run(args, book, cmd, paint):
    """Decide one write. Returns (lines to append, stdout lines, stderr lines, exit status)."""
    if args.command == "add":
        if args.recalled and args.date is None:
            return [], [], ["A recalled entry needs --date YYYY-MM-DD."], 2
        basis = "recalled" if args.recalled else "seen"
        new = Entry(args.date or today(), basis, normalise(" ".join(args.event)), one_line(" ".join(args.note)), 0)
        found = refusals(book.entries, [new])
        if found:
            _, message, old = found[0]
            fix = [f"To note a correction: {cmd} erratum {old.event} {old.date.year} <text>"] if old else []
            return [], [], [message] + fix, 1
        said = f"Entered. {new.event}, {fmt_date(new.date)}, {basis}. Day {doy(new.date)}."
        return [entry_line(new)], [said] + compare(book, new, paint), [], 0
    if args.command == "backfill":
        if sys.stdin.isatty():
            print("Paste one line per entry: YYYY-MM-DD event. End with Ctrl-D.")
        new, bad = read_paste(sys.stdin.read().split("\n"), "seen" if args.seen else "recalled")
        bad += [(new[i].line, message) for i, message, _ in refusals(book.entries, new)]
        if bad:
            said = [f"Line {n} {m}" if m.startswith("is ") else f"Line {n}: {m}" for n, m in sorted(bad)]
            return [], [], said + ["Nothing written."], 1
        if not new:
            return [], [], ["No lines read. Nothing written."], 1
        return [entry_line(e) for e in new], [f"{plural(len(new), 'line')} entered."], [], 0
    split = split_erratum(args.words, cmd)
    if isinstance(split, str):
        return [], [], [split], 2
    event, year, text = split
    target = next((e for e in book.entries if fold(e.event) == fold(event) and e.date.year == year), None)
    if target is None:
        return [], [], [f"No entry for {event}, {year}."], 1
    line = f"erratum | {year} | {target.event} | filed {today().isoformat()} | {text}"
    return [line], [f"Erratum filed against {target.event}, {year}. The entry stands."], [], 0


def main(argv=None):
    cmd = command_name(sys.argv[0])
    args = build_parser(cmd).parse_args(argv)
    path = os.environ.get("FIRSTS_FILE") or os.path.expanduser("~/firsts.txt")
    colour = sys.stdout.isatty() and not os.environ.get("NO_COLOR") and os.environ.get("COLORTERM") in ("truecolor", "24bit")

    def paint(s):
        return f"{BRICK}{s}{PLAIN}" if colour else s

    try:
        with open(path, "r", encoding="utf-8", errors="replace", newline="") as f:
            text = f.read()
    except FileNotFoundError:
        text = ""
    book = parse(text)
    for number, problem in book.problems:
        print(f"Line {number} {problem}", file=sys.stderr)

    if args.command in ("add", "backfill", "erratum"):
        new, out, err, status = run(args, book, cmd, paint)
        for line in err:
            print(line, file=sys.stderr)
        if not new:
            return status
        if not text:
            new = [HEADER, f"# Opened {today().isoformat()}."] + new
        elif not text.endswith("\n"):
            new[0] = "\n" + new[0]
        with open(path, "a", encoding="utf-8") as f:
            f.write("\n".join(new) + "\n")
        print("\n".join(out))
        if args.command != "backfill":
            print(path)
            return 0
        text += "\n".join(new) + "\n"
        book = parse(text)
        args.from_year, args.days = None, False

    if not book.entries:
        print("Nothing entered.")
        print(f"A first goes in with: {cmd} add <event>")
        print(f"Years already behind you go in with: {cmd} backfill")
        return 0
    from_year = getattr(args, "from_year", None)
    if from_year is not None and from_year > max(e.date.year for e in book.entries):
        print(f"Nothing entered from {from_year}.")
        return 0
    width = shutil.get_terminal_size().columns if sys.stdout.isatty() else 80
    print(path)
    print(render_table(book, from_year, getattr(args, "days", False), width, cmd, colour))
    return 0


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