"""Corrigenda of the Hand.

Reads one zsh or bash history file in memory and prints, as the corrigenda leaf
of a printed edition, the first-word slips its author keeps correcting, with an
alias block that makes each one stop mattering. It never writes a file.

    uv run corrigenda.py [HISTFILE] [-n N] [--aliases]
"""

import argparse
import os
import re
import shutil
import sys
from collections import Counter, namedtuple
from datetime import date, datetime

WIDTH = 72  # the page measure; a narrower terminal narrows it
WINDOW = 60  # seconds a correction may follow its slip when both carry a time
ZSH_LINE = re.compile(r": (\d+):\d+;(.*)", re.S)
BASH_TIME = re.compile(r"#(\d+)")
WORD = re.compile(r"[A-Za-z][A-Za-z0-9_-]{1,13}")  # 2 to 14 characters
SPLIT = re.compile(r"\s*(\S*)(.*)", re.S)
NBSP = "\u00a0"

# Builtins and reserved words of bash 5.2 and zsh 5.9 (compgen -b -k; ${(k)builtins} ${(k)reswords}).
BUILTINS = frozenset("""
    alias autoload bg bind bindkey break builtin bye caller case cd chdir command
    compadd comparguments compcall compctl compdescribe compfiles compgen complete
    compgroups compopt compquote compset comptags comptry compvalues continue coproc
    declare dirs disable disown do done echo echotc echoti elif else emulate enable
    end esac eval exec exit export false fc fg fi float for foreach function functions
    getln getopts hash help history if in integer jobs kill let limit local log logout
    mapfile nocorrect noglob popd print printf private pushd pushln pwd read readarray
    readonly rehash repeat return sched select set setopt shift shopt source suspend
    test then time times trap true ttyctl type typeset ulimit umask unalias unfunction
    unhash unlimit unset unsetopt until vared wait whence where which while zcompile
    zformat zle zmodload zparseopts zregexparse zstyle
""".split())

METHOD = (
    "Each entry was read against the one after it. A slip is a first word that "
    "names no command, followed by a known command a letter or two away with the "
    "rest of the line unchanged. A word stays on this leaf while its correction "
    "follows it at least half the times it is typed."
)
MACHINE = (
    "Commands were checked against the PATH of the machine that read the file, "
    "which need not be the machine that wrote it."
)
THINNING = (
    "Counts are what this file still holds. "
    "A shell set to drop duplicates or old entries holds fewer."
)

Entry = namedtuple("Entry", "line ts text")
Row = namedtuple("Row", "slip fix count line ts")


def parse(data):
    """Entries of a history file, each with its start line and time; and whether it is zsh extended."""
    # surrogateescape keeps every byte, so arguments compare byte for byte; zsh metafies non-ASCII.
    lines = data.decode("utf-8", "surrogateescape").split("\n")
    entries, zsh, stamp, more = [], False, None, False
    for n, line in enumerate(lines, 1):
        if more:  # zsh writes a multi-line command with a backslash at each line end
            last = entries[-1]
            entries[-1] = last._replace(text=last.text[:-1] + "\n" + line)
            more = line.endswith("\\")
            continue
        m = ZSH_LINE.fullmatch(line)
        if m:
            zsh, stamp, more = True, None, m[2].endswith("\\")
            entries.append(Entry(n, int(m[1]), m[2]))
            continue
        m = BASH_TIME.fullmatch(line)
        if m:
            stamp = int(m[1])
        elif line.strip():
            entries.append(Entry(n, stamp, line))
            stamp = None
    return entries, zsh


def distance(a, b):
    """Optimal string alignment distance: Levenshtein, plus a swap of two neighbours costs 1."""
    d = [[i + j if i * j == 0 else 0 for j in range(len(b) + 1)] for i in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] != b[j - 1]))
            if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
                d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
    return d[-1][-1]


def find(entries, on_path=shutil.which):
    """Rows of the slips that recur, dominant correction only, rate guard applied, ranked."""
    words = [SPLIT.match(e.text).groups() for e in entries]
    firsts = Counter(w for w, _ in words)
    real = {}

    def command(w):
        if w not in real:
            real[w] = w in BUILTINS or on_path(w) is not None
        return real[w]

    pairs, seen = Counter(), {}
    for i in range(1, len(entries)):
        (wa, ra), (wb, rb) = words[i - 1], words[i]
        a, b = entries[i - 1], entries[i]
        if wa == wb or ra != rb or not (WORD.fullmatch(wa) and WORD.fullmatch(wb)):
            continue
        if a.ts is not None and b.ts is not None and abs(b.ts - a.ts) > WINDOW:
            continue
        if command(wa) or not (command(wb) or firsts[wb] >= 3):
            continue
        if distance(wa, wb) > (1 if len(wb) <= 4 else 2):
            continue
        pairs[wa, wb] += 1
        seen.setdefault((wa, wb), a)

    rows, taken = [], set()
    for (wa, wb), n in sorted(pairs.items(), key=lambda p: (-p[1], seen[p[0]].line)):
        if wa in taken:  # only the dominant correction of each slip
            continue
        taken.add(wa)
        if n >= 2 and 2 * n >= firsts[wa]:  # the rate guard; an adopted alias retires its row
            rows.append(Row(wa, wb, n, seen[wa, wb].line, seen[wa, wb].ts))
    return rows


def day(ts):
    """The local date of a history time, or None when there is none or it is out of range."""
    try:
        return None if ts is None else datetime.fromtimestamp(ts).date().isoformat()
    except (OverflowError, OSError, ValueError):
        return None


def tilde(path):
    """An absolute path with $HOME written as ~ and anything unprintable as ?."""
    home, p = os.path.expanduser("~").rstrip("/"), os.path.abspath(path)
    if home and (p == home or p.startswith(home + "/")):
        p = "~" + p[len(home):]
    return "".join(c if c.isprintable() else "?" for c in p)


def wrap(text, width):
    """Lines of at most width where words allow; a longer word, such as a path, may break after a slash.

    Only a plain space breaks a line: a no-break space holds two words together and prints as a space.
    """
    lines, line = [], ""
    for word in filter(None, text.split(" ")):
        pieces = re.findall(r"[^/]*/|[^/]+", word) if len(word) > width else [word]
        if len(pieces) > 1 and line:  # a broken word starts on its own line
            lines.append(line)
            line = ""
        for i, piece in enumerate(pieces):
            glue = "" if i or not line else " "
            if line and len(line) + len(glue) + len(piece) > width:
                lines.append(line)
                line = piece
            else:
                line += glue + piece
    return [w.replace(NBSP, " ") for w in (lines + [line] if line else lines)]


def time_statement(entries):
    timed = sum(e.ts is not None for e in entries)
    if entries and timed == len(entries):
        return "Every entry carries a time. A correction counts if it follows within 60 seconds."
    if timed == 0:
        return "This history keeps no times. Corrections were taken from adjacent lines."
    return (
        f"{timed} of {len(entries)} entries carry times. Where both had one, the correction "
        "had to follow within 60 seconds; elsewhere adjacent lines were taken."
    )


def ledger(rows, bold):
    """Rows as sentences, padded so the counts read down a column aligned on the longest row."""
    parts = []
    for r in rows:
        place = f"line {r.line}" + (f", {day(r.ts)}" if day(r.ts) else "")
        parts.append((f"{place}: for {r.slip} read {r.fix},", str(r.count)))
    measure = max(len(s) + len(c) + 8 for s, c in parts)
    on, off = ("\x1b[1m", "\x1b[0m") if bold else ("", "")
    return [s + " " * (measure - len(s) - len(c) - 7) + on + c + off + " times." for s, c in parts]


def aliases(rows):
    return [f"alias {r.slip}='{r.fix}'" for r in rows]


def page(path, entries, rows, rc, width=WIDTH, bold=False):
    n = len(entries)
    out = ["", "CORRIGENDA".center(width).rstrip(), ""]
    for sentence in (f"to the shell history at {tilde(path)}, {n}{NBSP}{'entry' if n == 1 else 'entries'}.",
                     f"Read on {date.today().isoformat()}."):
        out += [line.center(width).rstrip() for line in wrap(sentence, width)]
    out.append("")
    if rows:
        out += ledger(rows, bold)
    else:
        out += wrap("No correction recurs in this history. The edition stands as printed.", width)
    out += ["", "* * *".center(width).rstrip()]
    for statement in (METHOD, MACHINE, time_statement(entries), THINNING):
        out += [""] + wrap(statement, width)
    out += ["", "Set in the typeface your terminal chose.", "normal is dead"]
    if rows:
        out += ["", "* * *".center(width).rstrip(), "", f"Errata slip, to be tipped in at {rc}", ""]
        out += aliases(rows)
    return "\n".join(out) + "\n"


def rc_file(zsh):
    """The rc file the alias block belongs in."""
    return "~/.zshrc" if zsh or os.environ.get("SHELL", "").endswith("zsh") else "~/.bashrc"


def locate(given):
    """The history file to read, or None, and every place looked."""
    if given:
        return (given if os.path.exists(given) else None), [given]
    home = os.path.expanduser("~")
    own = {"zsh": ".zsh_history", "bash": ".bash_history"}.get(os.path.basename(os.environ.get("SHELL", "")))
    places = [os.environ.get("HISTFILE") and os.path.expanduser(os.environ["HISTFILE"]),
              own and os.path.join(home, own),
              os.path.join(home, ".zsh_history"), os.path.join(home, ".bash_history")]
    places = list(dict.fromkeys(p for p in places if p))
    return next((p for p in places if os.path.isfile(p)), None), places


def rows_count(text):
    n = int(text)
    if n < 1:
        raise argparse.ArgumentTypeError("N must be 1 or more")
    return n


def main(argv=None):
    ap = argparse.ArgumentParser(prog="corrigenda.py", description="Print the corrigenda of a shell history.")
    ap.add_argument("histfile", nargs="?", metavar="HISTFILE", help="the history file (default: your own)")
    ap.add_argument("-n", type=rows_count, default=8, metavar="N", help="how many corrections to print (default 8)")
    ap.add_argument("--aliases", action="store_true", help="print only the alias block")
    args = ap.parse_args(argv)

    path, places = locate(args.histfile)
    if path is None:
        sys.stderr.write(f"No history file was found. Looked in: {', '.join(map(tilde, places))}.\n")
        return 2
    try:
        with open(path, "rb") as f:
            data = f.read()
    except OSError:
        sys.stderr.write(f"The history file at {tilde(path)} could not be read.\n")
        return 2
    # git's test for a binary file, a NUL in the first 8000 bytes; no shell writes one (zsh metafies it).
    if b"\0" in data[:8000]:
        sys.stderr.write(f"The file at {tilde(path)} does not read as a shell history.\n")
        return 2

    entries, zsh = parse(data)
    rows = find(entries)[: args.n]
    if args.aliases:
        sys.stdout.write("".join(line + "\n" for line in aliases(rows)))
        return 0
    tty = sys.stdout.isatty()
    width = WIDTH
    if tty:
        try:
            width = min(WIDTH, os.get_terminal_size(sys.stdout.fileno()).columns or WIDTH)
        except OSError:
            pass
    sys.stdout.write(page(path, entries, rows, rc_file(zsh), width, bold=tty and not os.environ.get("NO_COLOR")))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except BrokenPipeError:  # the reader went away (| head); say nothing
        os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
        sys.exit(1)
    except KeyboardInterrupt:
        sys.exit(130)
