#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Emporium Index: sorts a folder into thirteen classes, after Borges, 1942.

Every class is a property that find, stat or git log can confirm. A file may
belong to several classes, and the footer counts the overlap. Read-only,
except --write, which files the report in the folder it describes.
"""

import os
import stat
import subprocess
import sys
import textwrap
import time
import unicodedata
from collections import Counter
from typing import Callable, NamedTuple

DAY = 86400
AUDIO = frozenset("mp3 wav flac ogg opus m4a aac aif aiff wma mid midi".split())
IMAGE = frozenset("png jpg jpeg gif webp bmp tif tiff svg heic avif ico".split())
WORDMARK = "emporium index"
BRICK = "38;2;236;94;82"  # --c-brick #EC5E52, the one colour in the work
GIT_TIMEOUT = 30


class Entry:
    """One thing scandir yielded below DIR, with its lstat taken once."""

    __slots__ = ("rel", "name", "kind", "st", "children")

    def __init__(self, rel, name, kind, st):
        self.rel, self.name, self.kind, self.st = rel, name, kind, st
        self.children = 0  # direct entries, folders only

    def shown(self):
        return self.rel + "/" if self.kind == "d" else self.rel


class Ctx(NamedTuple):
    root: str
    now: float
    euid: int
    unread: list  # one slot, a counter the predicates may raise

    def path(self, e):
        return os.path.join(self.root, e.rel)


def ext(name):
    return os.path.splitext(name)[1][1:].lower()


def birth(st):
    return getattr(st, "st_birthtime", st.st_mtime)


def is_filed_report(e, c):
    """A report this tool filed earlier: the name, and the header as its first line."""
    if not (e.name.startswith("emporium-index") and e.name.endswith(".txt")):
        return False
    try:
        with open(c.path(e), "rb") as f:
            return f.read(len(WORDMARK)) == WORDMARK.encode()
    except OSError:
        c.unread[0] += 1
        return False


class Klass(NamedTuple):
    mark: str
    slug: str
    name: str
    prop: str
    test: str
    pred: Callable | None  # None: frenzied, which ranks the whole folder at once


def reg(e):
    return e.kind == "f"


# Borges's order. It never changes and does not rank. There is no (l).
CLASSES = (
    Klass("a", "emperor", "Belonging to the Emperor", "owner is not you",
          "not a folder or symlink; lstat st_uid is not your effective uid",
          lambda e, c: e.kind in "fo" and e.st.st_uid != c.euid),
    Klass("b", "embalmed", "Embalmed", "not writable by you",
          "regular file where os.access(path, W_OK) is false",
          lambda e, c: reg(e) and not os.access(c.path(e), os.W_OK)),
    Klass("c", "tame", "Tame", "not modified in 2 years",
          "regular file whose mtime is more than 730 days before now",
          lambda e, c: reg(e) and c.now - e.st.st_mtime > 730 * DAY),
    Klass("d", "sucking-pigs", "Sucking pigs", "created in the last 24 hours",
          "regular file; st_birthtime, else mtime, at most 24 h before now",
          lambda e, c: reg(e) and c.now - birth(e.st) <= DAY),
    Klass("e", "sirens", "Sirens", "audio file, by extension",
          "regular file with extension " + " ".join(sorted(AUDIO)) + ", any case",
          lambda e, c: reg(e) and ext(e.name) in AUDIO),
    Klass("f", "fabulous", "Fabulous", "symlink to nothing",
          "symlink whose target does not exist",
          lambda e, c: e.kind == "l" and not os.path.exists(c.path(e))),
    Klass("g", "stray-dogs", "Stray dogs", "no extension",
          "regular file; no dot in the name, so dotfiles are not strays",
          lambda e, c: reg(e) and "." not in e.name),
    Klass("h", "included", "Included in this classification", "written by this tool",
          "emporium-index*.txt starting \"emporium index\", and this report",
          lambda e, c: reg(e) and is_filed_report(e, c)),
    Klass("i", "frenzied", "Frenzied", "top 10 by git commits",
          "on disk, most commits in git log, at least 5, ties by path",
          None),
    Klass("j", "innumerable", "Innumerable", "over 1,000 entries",
          "folder with more than 1,000 direct entries (only folders)",
          lambda e, c: e.kind == "d" and e.children > 1000),
    Klass("k", "camelhair", "Drawn with a very fine camelhair brush", "image, by extension",
          "regular file with extension " + " ".join(sorted(IMAGE)) + ", any case",
          lambda e, c: reg(e) and ext(e.name) in IMAGE),
    Klass("m", "pitcher", "Having just broken the water pitcher", "modified in the last minute",
          "regular file whose mtime is 0 to 60 seconds before now",
          lambda e, c: reg(e) and 0 <= c.now - e.st.st_mtime <= 60),
    Klass("n", "flies", "That from a long way off resemble flies", "smaller than 64 bytes",
          "regular file with st_size under 64 bytes, empty files included",
          lambda e, c: reg(e) and e.st.st_size < 64),
)
BY_KEY = {k.mark: k for k in CLASSES} | {k.slug: k for k in CLASSES}
THIS_REPORT = "(this report)"


# walking

def kind_of(mode):
    if stat.S_ISREG(mode):
        return "f"
    if stat.S_ISDIR(mode):
        return "d"
    if stat.S_ISLNK(mode):
        return "l"
    return "o"


def walk(root):
    """Every entry below root, sorted by path as bytes (as LC_ALL=C sort would).

    Symlinks are not followed; folders named .git are skipped and not counted.
    Returns (entries, unreadable count, whether a .git folder was skipped).
    An unreadable root raises OSError.
    """
    entries, unread, skipped_git = [], 0, False
    stack = [(None, "")]
    while stack:
        parent, rel_dir = stack.pop()
        try:
            with os.scandir(os.path.join(root, rel_dir) if rel_dir else root) as it:
                items = list(it)
        except OSError:
            if parent is None:
                raise
            unread += 1
            continue
        for item in items:
            rel = f"{rel_dir}/{item.name}" if rel_dir else item.name
            try:
                st = item.stat(follow_symlinks=False)
            except OSError:
                unread += 1
                e = Entry(rel, item.name, "?", None)
            else:
                e = Entry(rel, item.name, kind_of(st.st_mode), st)
                if e.kind == "d" and item.name == ".git":
                    skipped_git = True
                    continue
                if e.kind == "d":
                    stack.append((e, rel))
            entries.append(e)
            if parent is not None:
                parent.children += 1
    entries.sort(key=lambda e: os.fsencode(e.rel))
    return entries, unread, skipped_git


# git

def git_counts(root):
    """Commit count per path from git log, or the reason it could not be had."""
    cmd = ["git", "-C", root, "-c", "log.showSignature=false", "log", "-z", "--relative",
           "--name-only", "--no-renames", "--pretty=format:"]
    env = os.environ | {"LC_ALL": "C", "LANGUAGE": "C", "GIT_OPTIONAL_LOCKS": "0"}
    try:
        p = subprocess.run(cmd, capture_output=True, timeout=GIT_TIMEOUT, env=env, stdin=subprocess.DEVNULL)
    except FileNotFoundError:
        return None, "git was not found on this system."
    except subprocess.TimeoutExpired:
        return None, f"git log took longer than {GIT_TIMEOUT} seconds."
    except OSError:
        return None, "git could not be started."
    if p.returncode != 0:
        err = p.stderr.decode(errors="replace").lower()
        if "not a git repository" in err:
            return None, "This folder is not inside a git repository."
        if "does not have any commits" in err:
            return None, "This repository has no commits yet."
        return None, f"git log failed with exit status {p.returncode}."
    # -z: names end in NUL, commits are separated by an empty name; names stay exact
    return Counter(os.fsdecode(n) for n in p.stdout.split(b"\0") if n), None


def frenzied(counts, by_rel):
    ranked = sorted(((n, rel) for rel, n in counts.items() if n >= 5),
                    key=lambda t: (-t[0], os.fsencode(t[1])))
    out = []
    for n, rel in ranked:
        e = by_rel.get(rel)
        if e is not None and e.kind == "f":
            out.append(e)
            if len(out) == 10:
                break
    return out


# counting

def count(root, now):
    entries, unread, skipped_git = walk(root)
    c = Ctx(root, now, os.geteuid(), [0])
    members = {}
    for k in CLASSES:
        if k.pred is not None:
            members[k.slug] = [e for e in entries if e.st is not None and k.pred(e, c)]
    counts, git_reason = git_counts(root)
    members["frenzied"] = frenzied(counts, {e.rel: e for e in entries}) if counts is not None else []

    notes = []
    if git_reason:
        notes.append(f"Frenzied was not counted. {git_reason}")
    regs = [e for e in entries if e.kind == "f"]
    if regs and not hasattr(regs[0].st, "st_birthtime"):
        notes.append("Sucking pigs uses modification time. This system reports no creation time.")
    if len(regs) >= 10:
        minute, n = Counter(int(e.st.st_mtime // 60) for e in regs).most_common(1)[0]
        if 2 * n >= len(regs):
            when = time.strftime("%Y-%m-%d %H:%M", time.localtime(minute * 60))
            notes.append(f"{n:,} of {len(regs):,} files share one modification time ({when}). "
                         "Age classes may describe a copy, not use.")
    unread += c.unread[0]
    if unread:
        notes.append(f"{unread:,} {'entry' if unread == 1 else 'entries'} could not be read.")

    placed = {id(e) for group in members.values() for e in group}
    totals = {slug: len(group) for slug, group in members.items()}
    totals["included"] += 1  # the report being made
    placements = sum(totals.values())
    classified = len(placed) + 1
    name = os.path.basename(os.path.abspath(root).rstrip("/")) or "/"
    return {
        "name": name, "now": now, "members": members, "totals": totals,
        "on_disk": len(entries), "classified": classified, "placements": placements,
        "surplus": placements - classified, "notes": notes, "skipped_git": skipped_git,
    }


# text

def clean(s):
    """Control characters, escape sequences and undecodable bytes become '?'."""
    return "".join("?" if (o := ord(ch)) < 32 or 127 <= o < 160 or 0xD800 <= o < 0xE000 else ch
                   for ch in s)


def width_of(s):
    return sum(0 if unicodedata.combining(ch) else 2 if unicodedata.east_asian_width(ch) in "WF" else 1
               for ch in s)


def cut(s, w):
    if width_of(s) <= w:
        return s
    out, used = [], 0
    for ch in s:
        cw = width_of(ch)
        if used + cw > w - 3:
            break
        out.append(ch)
        used += cw
    return "".join(out) + "..."


class Style(NamedTuple):
    on: bool  # bold and dim, on a terminal only
    rgb: bool  # the brick rule, on a truecolor terminal without NO_COLOR

    def sgr(self, code, s):
        return f"\x1b[{code}m{s}\x1b[0m" if self.on and s else s


PLAIN = Style(False, False)


def line(style, *parts):
    """parts are text or (sgr code, text); returns (plain, styled)."""
    plain = "".join(p if isinstance(p, str) else p[1] for p in parts)
    styled = "".join(p if isinstance(p, str) else style.sgr(*p) for p in parts)
    return plain, styled


def pack(pieces, w, gap="   "):
    rows, cur = [], ""
    for p in pieces:
        if cur and width_of(cur + gap + p) > w:
            rows.append(cur)
            cur = p
        else:
            cur = cur + gap + p if cur else p
    return rows + [cur]


def header(style, w, title, pieces):
    title = cut(clean(title), w - len(WORDMARK) - 3)
    rule = "=" * len(WORDMARK)
    out = [line(style, ("1", "emporium"), " index   ", title)]
    out += [line(style, row) for row in pack(pieces, w)]
    out.append((rule, f"\x1b[{BRICK}m{rule}\x1b[0m" if style.rgb else rule))
    return out


def examples(slug, group):
    names = [clean(e.shown()) for e in group]
    if slug == "included":
        names.append(THIS_REPORT)
    return ", ".join(names[:3])


def report(d, w=80, style=PLAIN):
    """The report as a list of lines, styled for a terminal or plain for a file or pipe."""
    when = time.strftime("%Y-%m-%d %H:%M", time.localtime(d["now"]))
    pieces = ["after Borges, 1942", f"counted {when}"] + (["skipped .git"] if d["skipped_git"] else [])
    out = header(style, w, d["name"], pieces) + [("", "")]

    shown = [k for k in CLASSES if d["totals"][k.slug]]
    nw = max(len(k.name) for k in shown)
    cw = max(2, *(len(f"{d['totals'][k.slug]:,}") for k in shown))  # "flies  3", as on the card
    split = any(5 + nw + 1 + cw + 2 + len(k.prop) > w for k in shown)
    for k in shown:
        n = f"{d['totals'][k.slug]:,}"
        ex = ("2", "     " + cut(examples(k.slug, d["members"][k.slug]), w - 5))
        if split:  # a terminal narrower than the card: the count drops under the name
            out.append(line(style, f"({k.mark})  ", ("1", cut(k.name, w - 5))))
            out.append(line(style, f"     {n}  ", ("2", cut(k.prop, w - 7 - len(n)))))
        else:
            out.append(line(style, f"({k.mark})  ", ("1", k.name), " " * (nw - len(k.name)),
                            f" {n:>{cw}}  ", ("2", k.prop)))
        out.append(line(style, ex))

    rows = [("entries", d["on_disk"] + 1), ("classified", d["classified"]),
            ("placements", d["placements"]), ("surplus", d["surplus"])]
    aside = f"{d['on_disk']:,} on disk, and this report"
    nwid = max(8, max(len(f"{v:,}") for _, v in rows) + 2)
    if 10 + nwid + 3 + len(aside) > w:  # a narrow terminal: close the column up first
        nwid = max(len(f"{v:,}") for _, v in rows) + 1
    out.append(("", ""))
    for label, v in rows:
        row = f"{label:<10}{v:>{nwid},}"
        if label == "entries":
            if len(row) + 3 + len(aside) <= w:
                row += "   " + aside
            else:
                out.append(line(style, row))
                row = " " * 10 + aside
        out.append(line(style, row))

    if d["notes"]:
        out.append(("", ""))
        for note in d["notes"]:
            for row in textwrap.wrap("Note: " + note, w, subsequent_indent="      "):
                out.append(line(style, row))
    return out


def classes_page(w=80, style=PLAIN):
    out = header(style, w, "classes", ["after Borges, 1942"]) + [("", "")]

    def card(left, text, code=None):  # a hanging indent: mark and slug in the margin
        rows = textwrap.wrap(text, w - 17) or [""]
        for i, row in enumerate(rows):
            out.append(line(style, (left if i == 0 else "").ljust(17), (code, row) if code else row))

    for k in CLASSES:
        if k.mark == "m":
            card("l  et cetera", "no property to check, not implemented.")
        card(f"{k.mark}  {k.slug}", k.prop, "2")
        card("", k.name, "1")
        card("", k.test, "2")
    out.append(("", ""))
    for row in textwrap.wrap("The order is Borges's and never ranks. Symlinks are not followed. "
                             "Folders named .git are skipped. No file is read except the first "
                             "line of a filed report.", w):
        out.append(line(style, row))
    return out


USAGE = (
    ("emporium [CLASS|MARK] [DIR]", "report, or the paths in one class"),
    ("emporium [DIR] --write", "also file the report in DIR, named for the minute"),
    ("emporium --classes", "the thirteen classes, slugs and exact tests"),
    ("emporium --help", ""),
)
ABOUT = (
    "DIR is the current folder unless given. CLASS is a slug or a mark letter: "
    "emporium g and emporium stray-dogs are the same. A class prints its paths, one per line, "
    "and exits 0 if there are any, 1 if none, 2 on a usage error.",
    "Nothing is changed, except that --write adds one dated file to DIR.",
)


def help_text(w=80):
    rows = ["emporium index", *textwrap.wrap("Sorts a folder into classes. A file may belong to several.", w), ""]
    for cmd, what in USAGE:
        if w >= 80:
            rows.append(f"  {cmd:<27}  {what}".rstrip())
        else:  # narrow: the description goes under its command
            rows.append("  " + cmd)
            rows += textwrap.wrap(what, w, initial_indent="      ", subsequent_indent="      ")
    for para in ABOUT:
        rows += [""] + textwrap.wrap(para, w)
    return "\n".join(rows)


def unknown(arg):
    listed = "; ".join(f"{k.mark} {k.prop}" for k in CLASSES)
    return f'Unknown class "{clean(arg)}". Classes: {listed}. See emporium --classes.'


# running

def width(stream):
    """The card's 80 columns, narrower only on a narrower terminal."""
    try:
        return max(40, min(80, os.get_terminal_size(stream.fileno()).columns))
    except (OSError, ValueError):
        return 80


def fail(msg, code=2):
    if sys.stderr.isatty():
        msg = textwrap.fill(msg, width(sys.stderr))
    print(msg, file=sys.stderr)
    return code


def term():
    """(width, style) for stdout. Bold and dim on a terminal; the brick rule only on a
    truecolor one without NO_COLOR; nothing at all in a pipe or a file."""
    if not sys.stdout.isatty() or os.environ.get("TERM") == "dumb":
        return 80, PLAIN
    rgb = not os.environ.get("NO_COLOR") and os.environ.get("COLORTERM") in ("truecolor", "24bit")
    return width(sys.stdout), Style(True, rgb)


def emit(lines, styled):
    print("\n".join(s if styled else p for p, s in lines))


def main(argv):
    flags, pos = set(), []
    for a in argv:
        if a in ("--help", "-h", "--classes", "--write"):
            flags.add(a)
        elif a.startswith("-") and a != "-":
            return fail(f'Unknown option "{clean(a)}". See emporium --help.')
        else:
            pos.append(a)
    if flags & {"--help", "-h"}:
        print(help_text(term()[0]))
        return 0
    if "--classes" in flags:
        w, style = term()
        emit(classes_page(w, style), style.on)
        return 0
    if len(pos) > 2:
        return fail("Too many arguments. See emporium --help.")

    klass, root = None, "."
    if len(pos) == 2:
        klass = BY_KEY.get(pos[0])
        if klass is None:
            return fail(unknown(pos[0]))
        root = pos[1]
        if not os.path.isdir(root):
            return fail(f'Not a folder: "{clean(root)}".')
    elif pos:
        klass = BY_KEY.get(pos[0])
        if klass is None:
            if not os.path.isdir(pos[0]):
                return fail(unknown(pos[0]))
            root = pos[0]
    if klass and "--write" in flags:
        return fail("--write takes the whole report.")

    now = time.time()  # the one instant every age test uses
    try:
        d = count(root, now)
    except OSError as e:
        return fail(f'Cannot read "{clean(root)}": {e.strerror}.')

    if klass:
        group = d["members"][klass.slug]
        if not group:
            return fail("No entries.", 1)
        out = sys.stdout.buffer
        if sys.stdout.isatty():
            out.write("".join(clean(e.rel) + "\n" for e in group).encode("utf-8", "replace"))
        else:  # exact bytes, as find would print them
            out.write(b"".join(os.fsencode(e.rel) + b"\n" for e in group))
        out.flush()
        return 0

    w, style = term()
    if "--write" in flags:
        fname = time.strftime("emporium-index-%Y-%m-%d-%H%M.txt", time.localtime(now))
        try:
            with open(os.path.join(root, fname), "x", encoding="utf-8") as f:
                f.write("\n".join(p for p, _ in report(d)) + "\n")
        except FileExistsError:
            return fail("A report for this minute is already filed.", 1)
        except OSError as e:
            return fail(f"Could not file the report: {e.strerror}.", 1)
        emit(report(d, w, style), style.on)
        sys.stdout.flush()  # the report first, then the receipt
        print(f"Filed as {fname}.", file=sys.stderr)
        return 0
    emit(report(d, w, style), style.on)
    return 0


if __name__ == "__main__":
    sys.stdout.reconfigure(errors="replace")
    try:
        sys.exit(main(sys.argv[1:]))
    except BrokenPipeError:  # emporium g | head
        os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
        sys.exit(1)
    except KeyboardInterrupt:
        sys.exit(130)
