#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""itemised: runs a command, then prints a till receipt of the files it created,
changed and removed, ending in the net bytes as Amount due or Change due.

usage: itemised [--also PATH]... [--full] [--limit N] [--] COMMAND [ARGS...]
"""

from __future__ import annotations

import os
import shlex
import shutil
import signal
import subprocess
import sys
import time
import unicodedata
import zlib
from collections import Counter
from dataclasses import dataclass, field
from datetime import datetime

W = 48  # receipt width in display columns
GROUP = 20  # a directory holding more items than this in one list is one row
LIMIT = 250_000  # default entry budget for each top-level directory
SLACK = 16 * 1024 * 1024  # volume movement the receipt may leave unexplained
KINDS = ("created", "changed", "removed")
RULE = "=" * W
PAPER = "\x1b[48;2;252;240;221m\x1b[38;2;26;26;26m"  # cream paper, ink print
RESET = "\x1b[0m"
USAGE = "usage: itemised [--also PATH]... [--full] [--limit N] [--] COMMAND [ARGS...]"
CONTROLS = {c: f"\\x{c:02x}" for c in (*range(0x20), *range(0x7F, 0xA0))}

Stat = tuple[int, int, int, int]  # size, mtime_ns, ctime_ns, mode


# Names and columns


def shown(name: str) -> str:
    """The name as printed: each undecodable byte and each control character
    becomes \\xNN, a backslash becomes two. Nothing on disk is altered."""
    if name.isprintable() and "\\" not in name:
        return name
    parts = os.fsencode(name).split(b"\\")
    text = "\\\\".join(p.decode("utf-8", "backslashreplace") for p in parts)
    return text.translate(CONTROLS)


def cols(c: str) -> int:
    if unicodedata.category(c) in ("Mn", "Me", "Cf"):
        return 0
    return 2 if unicodedata.east_asian_width(c) in ("W", "F") else 1


def width(s: str) -> int:
    """Columns a terminal draws, not characters counted."""
    return len(s) if s.isascii() else sum(cols(c) for c in s)


def cut(s: str) -> tuple[str, str]:
    """Split after W columns; a wide character never straddles the edge."""
    n = 0
    for i, c in enumerate(s):
        n += cols(c)
        if n > W:
            return s[:i], s[i:]
    return s, ""


def hard(s: str) -> list[str]:
    """Hard wrap at W columns, no indent: the pieces join back to s."""
    rows = []
    while width(s) > W:
        head, s = cut(s)
        rows.append(head)
    return [*rows, s]


def wrap(text: str) -> list[str]:
    """Word wrap at W columns, continuation rows indented by two spaces."""
    rows: list[str] = []
    line: str | None = None
    for word in text.split(" "):
        cand = word if line is None else f"{line} {word}"
        if width(cand) > W and line is not None and line.strip():
            rows.append(line)
            cand = f"  {word}"
        line = cand
        while width(line) > W:
            head, rest = cut(line)
            rows.append(head)
            line = f"  {rest}"
    return [*rows, line or ""]


def lr(left: str, right: str) -> list[str]:
    """Left text and right-aligned text on one row; a left side that does
    not fit is hard wrapped and the right side ends the last row."""
    rows = hard(left)
    gap = W - width(rows[-1]) - width(right)
    if gap >= 1:
        rows[-1] += " " * gap + right
    else:
        rows.append(" " * (W - width(right)) + right)
    return rows


def center(s: str) -> str:
    return " " * ((W - width(s)) // 2) + s


# Amounts


def human(n: int) -> str:
    """Decimal units, one decimal, as Finder and disk vendors count."""
    n = abs(n)
    if n < 1000:
        return f"{n} B"
    v = float(n)
    for unit in ("kB", "MB", "GB", "TB"):
        v /= 1000
        if float(f"{v:.1f}") < 1000:
            break
    return f"{v:.1f} {unit}"


def sized(n: int, kind: str) -> str:
    sign = {"created": "+", "removed": "-"}.get(kind)
    return f"{sign or ('+' if n > 0 else '-' if n < 0 else '')}{human(n)}"


def exact(n: int) -> str:
    return f"{n:+,} B" if n else "0 B"


def dur(t: float) -> str:
    if t < 59.95:
        return f"{t:.1f} s"
    m, s = divmod(round(t), 60)
    return f"{m} min {s:02d} s"


def gb(n: int) -> str:
    return f"{n / 1e9:.2f} GB" if n >= 1e9 else f"{n / 1e6:.2f} MB"


# The count


@dataclass
class Snap:
    files: dict[str, Stat] = field(default_factory=dict)
    skipped: set[str] = field(default_factory=set)
    dropped: set[str] = field(default_factory=set)
    unreadable: set[str] = field(default_factory=set)

    def absorb(self, other: Snap) -> None:
        self.files.update(other.files)
        self.skipped |= other.skipped
        self.dropped |= other.dropped
        self.unreadable |= other.unreadable


def snapshot(
    roots: list[tuple[str, str]], limit: int, scope: Snap | None = None
) -> Snap:
    """lstat every non-directory entry under each (path, printed prefix) root.

    Symlinks are recorded, never followed; .git is never entered. In the before
    snapshot (no scope) each top-level directory is walked with an entry budget
    and dropped whole when over it. The after snapshot keeps the before scope
    and walks it fully, so a dropped subtree never shows as a false change.
    """
    notice = time.monotonic() + 2

    def walk(top: str, prefix: str, budget: int | None, split: bool) -> Snap | None:
        nonlocal notice
        part, stack, count = Snap(), [(top, prefix)], 1
        while stack:
            path, p = stack.pop()
            try:
                with os.scandir(path) as it:
                    entries = list(it)
            except FileNotFoundError:
                continue  # gone, so everything under it was removed
            except OSError:
                part.unreadable.add(p or "./")
                continue
            count += len(entries)
            if budget is not None and count > budget:
                return None
            if time.monotonic() > notice:
                print("itemised: counting", file=sys.stderr, flush=True)
                notice = float("inf")
            for e in entries:
                q = p + shown(e.name)
                try:
                    is_dir = e.is_dir(follow_symlinks=False)
                    st = None if is_dir else e.stat(follow_symlinks=False)
                except OSError:
                    continue  # removed between listing and lstat
                if st is not None:
                    part.files[q] = (
                        st.st_size,
                        st.st_mtime_ns,
                        st.st_ctime_ns,
                        st.st_mode,
                    )
                elif e.name == ".git":
                    part.skipped.add(f"{q}/")
                elif not split:
                    stack.append((e.path, f"{q}/"))
                elif scope is not None and f"{q}/" in scope.dropped:
                    part.dropped.add(f"{q}/")
                else:
                    sub = walk(e.path, f"{q}/", limit if scope is None else None, False)
                    if sub is None:
                        part.dropped.add(f"{q}/")
                    else:
                        part.absorb(sub)
        return part

    snap = Snap()
    for root, prefix in roots:
        snap.absorb(walk(root, prefix, None, True) or Snap())
    return snap


def diff(before: dict[str, Stat], after: dict[str, Stat]) -> dict[str, dict[str, int]]:
    """Signed sizes per kind: created +length, changed by the difference in
    length, removed -length. Changed: size, mtime, ctime or mode differs."""
    return {
        "created": {p: s[0] for p, s in after.items() if p not in before},
        "changed": {
            p: s[0] - before[p][0]
            for p, s in after.items()
            if p in before and s != before[p]
        },
        "removed": {p: -s[0] for p, s in before.items() if p not in after},
    }


def number(items: dict[str, dict[str, int]]) -> str:
    """CRC32 of the sorted KIND PATH SIZE lines, one per file, no times: the
    same work on the same tree gives the same number on any day."""
    lines = sorted(
        f"{k} {p} {v if k == 'changed' else abs(v)}"
        for k in KINDS
        for p, v in items[k].items()
    )
    data = "".join(x + "\n" for x in lines).encode()
    return f"{zlib.crc32(data):08X}"


def ancestors(path: str, prefixes: list[str]) -> list[str]:
    """Directories above path, outermost first, never the root itself.
    prefixes run longest first and end with "" for the working directory."""
    # ponytail: a relative name starting with "~/" that matches an --also
    # prefix is grouped as if in that root; only the grouping row differs.
    root = next(r for r in prefixes if path.startswith(r))
    parts = path[len(root) :].split("/")[:-1]
    return [root + "/".join(parts[: i + 1]) + "/" for i in range(len(parts))]


def group(
    items: dict[str, int], prefixes: list[str], full: bool = False
) -> list[tuple[str, int, int]]:
    """Rows of (printed path, files, summed size), sorted by path. A directory
    holding more than GROUP items is one row; the outermost such wins."""
    if full:
        return sorted((p, 1, v) for p, v in items.items())
    above = {p: ancestors(p, prefixes) for p in items}
    counts = Counter(d for ds in above.values() for d in ds)
    rows: dict[str, list[int]] = {}
    for p, v in items.items():
        key = next((d for d in above[p] if counts[d] > GROUP), p)
        row = rows.setdefault(key, [0, 0])
        row[0] += 1
        row[1] += v
    return sorted((k, c, s) for k, (c, s) in rows.items())


# The slip


@dataclass
class Run:
    argv: list[str]
    when: str
    cwd: str
    items: dict[str, dict[str, int]]
    also: list[str] = field(default_factory=list)
    prefixes: list[str] = field(default_factory=lambda: [""])
    full: bool = False
    limit: int = LIMIT
    exit: int = 0
    elapsed: float = 0.0
    counting: float = 0.0
    free: tuple[int | None, int | None] = (None, None)
    elsewhere: list[str] = field(default_factory=list)
    skipped: set[str] = field(default_factory=set)
    dropped: set[str] = field(default_factory=set)
    unreadable: set[str] = field(default_factory=set)


def render(run: Run) -> list[str]:
    items = run.items
    net = sum(sum(v.values()) for v in items.values())
    rows = [center("itemised"), center("normal is dead"), RULE]
    rows += lr(run.when, f"No. {number(items)}")
    rows += wrap(f"Served by: {shown(os.path.basename(run.argv[0]))}")
    rows += wrap(shown(shlex.join(run.argv)))
    rows += wrap(f"in {run.cwd}")
    rows += [r for p in run.also for r in wrap(f"and {p}")]
    rows.append(RULE)

    if not any(items.values()):
        rows.append("No items.")
    for kind in KINDS:
        if items[kind]:
            rows.append(kind.upper())
            for path, n, size in group(items[kind], run.prefixes, run.full):
                label = f"{path} x {n:,}" if path.endswith("/") else path
                rows += lr(label, sized(size, kind))
    rows.append(RULE)

    for kind in KINDS:
        n = len(items[kind])
        left = f"{kind:<7}{n:>7,} {'file' if n == 1 else 'files'}"
        rows += lr(left, exact(sum(items[kind].values())))
    rows += lr("net", exact(net))
    rows += lr(f"exit {run.exit}  {dur(run.elapsed)}", f"counting {dur(run.counting)}")
    f0, f1 = run.free
    known = f0 is not None and f1 is not None
    rows += lr(
        "volume free", f"{gb(f0)} before, {gb(f1)} after" if known else "unknown"
    )
    rows += [
        r for p in run.elsewhere for r in wrap(f"  other volume, not counted: {p}")
    ]
    if known:
        away = tuple(run.elsewhere)
        here = net - sum(
            v for k in KINDS for p, v in items[k].items() if p.startswith(away)
        )
        off = (f0 - f1) - here
        if abs(off) >= SLACK:
            way = "more" if off > 0 else "less"
            rows += wrap(f"Not itemised: {human(off)} {way} used than itemised")
    rows.append(RULE)

    if run.skipped:
        s = sorted(run.skipped)
        more = f" and {len(s) - 5:,} more" if len(s) > 5 else ""
        rows += wrap(f"Skipped: {', '.join(s[:5])}{more}")
    for d in sorted(run.dropped):
        rows += wrap(f"Not examined: {d} (over {run.limit:,} entries)")
    if run.unreadable:
        u = sorted(run.unreadable)
        if len(u) == 1:
            rows += wrap(f"Not examined: 1 unreadable directory: {u[0]}")
        else:
            rows += wrap(
                f"Not examined: {len(u):,} unreadable directories, first: {u[0]}"
            )
    rows.append("Not examined: made and removed during the run")
    rows.append("Not examined: file contents, only size and times")
    outside = "the paths listed above" if run.also else "the working directory"
    rows.append(f"Not examined: outside {outside}")
    rows.append(RULE)

    if net > 0:
        rows += lr("Amount due", human(net))
    elif net < 0:
        rows += lr("Change due", human(net))
    else:
        rows.append("Nothing due.")
    return rows


def paint(rows: list[str], colour: bool) -> str:
    """Plain rows, or rows on cream paper in ink, each padded to the full
    width, with one blank paper row above and below."""
    if not colour:
        return "".join(f"{r}\n" for r in rows)
    pad = ["", *rows, ""]
    return "".join(f"{PAPER}{r}{' ' * (W - width(r))}{RESET}\n" for r in pad)


def wants_colour() -> bool:
    return (
        sys.stderr.isatty()
        and not os.environ.get("NO_COLOR")
        and os.environ.get("COLORTERM") in ("truecolor", "24bit")
    )


# The run


class Usage(Exception):
    pass


def parse(argv: list[str]) -> tuple[list[str], bool, int, list[str]]:
    also: list[str] = []
    full, limit, i = False, LIMIT, 0
    while i < len(argv) and argv[i].startswith("-"):
        flag = argv[i]
        i += 1
        if flag == "--":
            break
        if flag == "--full":
            full = True
        elif flag in ("--also", "--limit"):
            if i == len(argv):
                raise Usage(f"{flag} needs a value")
            value = argv[i]
            i += 1
            if flag == "--also":
                also.append(value)
            elif value.isdecimal() and int(value) > 0:
                limit = int(value)
            else:
                raise Usage("--limit needs a whole number above 0")
        elif flag in ("-h", "--help"):
            raise Usage("")
        else:
            raise Usage(f"unknown option: {shown(flag)}")
    return also, full, limit, argv[i:]


def tilde(path: str) -> str:
    """The path with the home directory shown as ~."""
    raw = os.path.expanduser("~")
    if not os.path.isabs(raw):
        return path
    for home in dict.fromkeys((raw, os.path.realpath(raw))):
        home = home.rstrip("/")
        if home and (path == home or path.startswith(f"{home}/")):
            return "~" + path[len(home) :]
    return path


def outermost(paths: list[str]) -> list[str]:
    """The roots in the order given, without any root contained in another."""
    paths = list(dict.fromkeys(paths))
    return [
        p
        for p in paths
        if not any(q != p and p.startswith(q.rstrip("/") + "/") for q in paths)
    ]


def free_bytes(path: str) -> int | None:
    try:
        return shutil.disk_usage(path).free
    except OSError:
        return None


def execute(cmd: list[str]) -> int:
    """Run cmd with stdin, stdout and stderr inherited; return its returncode
    (negative when a signal ended it).

    Ctrl-C and Ctrl-\\ reach the child as usual. The wrapper catches them with a
    handler that does nothing, so it lives to print the receipt. Nothing is
    ignored before the spawn: exec resets a caught signal to its default in
    the child, so the child starts with exactly the dispositions it would have
    had without the wrapper, and there is no instant in which the wrapper can
    be interrupted between the spawn and the wait."""
    sigs = (signal.SIGINT, signal.SIGQUIT)
    saved = {s: signal.getsignal(s) for s in sigs}
    try:
        for s in sigs:
            if saved[s] is not signal.SIG_IGN:  # inherited SIG_IGN stays as given
                signal.signal(s, lambda *_: None)
        rc = subprocess.Popen(cmd).wait()
    finally:
        for s, handler in saved.items():
            signal.signal(s, handler)
    return rc


def main(argv: list[str] | None = None) -> int:
    try:
        also, full, limit, cmd = parse(sys.argv[1:] if argv is None else argv)
        if not cmd:
            raise Usage("nothing to run. Give a command, for example: itemised ls")
        for path in also:
            if not os.path.isdir(path):
                what = "not a directory" if os.path.exists(path) else "no such path"
                raise Usage(f"{what}: {shown(path)}")
    except Usage as e:
        if not str(e):
            print(USAGE)
            return 0
        print(f"itemised: {e}\n{USAGE}", file=sys.stderr)
        return 2

    cwd = os.path.realpath(os.getcwd())
    roots = outermost([cwd, *(os.path.realpath(p) for p in also)])
    pairs = [(r, "" if r == cwd else shown(tilde(r)).rstrip("/") + "/") for r in roots]
    dev = os.stat(cwd).st_dev
    elsewhere = [p for r, p in pairs if os.stat(r).st_dev != dev]
    prefixes = [*sorted((p for _, p in pairs), key=len, reverse=True), ""]

    t0 = time.monotonic()
    free0 = free_bytes(cwd)
    before = snapshot(pairs, limit)
    when = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    t1 = time.monotonic()
    try:
        rc = execute(cmd)
    except FileNotFoundError:
        print(f"itemised: not found: {shown(cmd[0])}", file=sys.stderr)
        return 127
    except OSError:
        print(f"itemised: cannot run: {shown(cmd[0])}", file=sys.stderr)
        return 126
    t2 = time.monotonic()
    code = 128 - rc if rc < 0 else rc
    after = snapshot(pairs, limit, before)
    free1 = free_bytes(cwd)
    t3 = time.monotonic()

    run = Run(
        argv=cmd,
        when=when,
        cwd=shown(tilde(cwd)),
        items=diff(before.files, after.files),
        also=[shown(tilde(r)) for r in roots if r != cwd],
        prefixes=prefixes,
        full=full,
        limit=limit,
        exit=code,
        elapsed=t2 - t1,
        counting=(t1 - t0) + (t3 - t2),
        free=(free0, free1),
        elsewhere=elsewhere,
        skipped=before.skipped | after.skipped,
        dropped=before.dropped,
        unreadable=before.unreadable | after.unreadable,
    )
    # The terminal echoed ^C or ^\ and left the cursor after it; the shell
    # would start a new line here, so the receipt does.
    echoed = rc in (-signal.SIGINT, -signal.SIGQUIT) and sys.stderr.isatty()
    sys.stderr.write("\n" * echoed + paint(render(run), wants_colour()))
    sys.stderr.flush()
    return code


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:  # only while counting, before or after the run
        sys.exit(130)
