#!/usr/bin/env python3
"""Index recipe. The self owns this file; it imports nothing from brnrd.

    core/loom/index [--rev REV] [--write | --check [--old REV]]

Reads one committed tree (HEAD by default) through git, so a room, a bare
hook with GIT_DIR, and a person's checkout all see the same thing, and
prints INDEX.md to stdout. --write writes INDEX.md, CLAUDE.md as a copy of
AGENTS.md when AGENTS.md is in the tree (CLAUDE.md is removed when it is
not), and one memory/scars/<domain>/index.md per folder that holds scars
(removed when the folder holds none). --check compares each of them at REV
with the regeneration and exits 1 naming each that differs; INDEX.md or
CLAUDE.md absent at both --old and REV passes, and so does a scar folder
that had scars and no index at --old, so a self from before the index lands
its first one through send-self. Exit 2 is a broken recipe.

A scar is one file at memory/scars/<domain>/<slug>.md. Its folder index
reads title, trigger words and date from the scar's head: the frontmatter
plus the first SCAR_HEAD non-blank lines after it, title included. The
`trigger:` line (or frontmatter key) and the YYYY-MM-DD date are what
core/immune.d/45-scars refuses a changed scar without; the same head is
read here, so the two agree on where a scar's trigger and date must sit.

Topic pages (topics/<slug>.md) come first, one row each: title, entry
count (its `### ` lines) and size, alphabetical, topics/README.md linked
from the section's head when the tree has it.

Generation only derives from what a writer already wrote: titles, first
lines, sizes, frontmatter, wish lines, link targets. It never summarises,
never moves a file and never closes anything. Order is newest first by the
commit that last touched a path, counted in topological order, so the same
tree gives the same index after a rebase or a relabel.

Open threads split by when their folder was last written, by author time
measured from the newest author time in the history, so a rebase does not
move a thread between groups: moving (within QUIET_DAYS), quiet (older, its
age shown), and untouched since opened (no commit after the one that made
the folder wrote to it alone; sweeps across many threads do not count).
A thread row prints its wish line in place of its first line when it has
one: the first line is often the spec's head, and the wish is its purpose.
"""

from __future__ import annotations

import re
import subprocess
import sys
from pathlib import Path

ROOTS = ("topics", "threads", "memory", "people")
OPEN = ("open", "live", "dormant")
HEADLINE = 200
QUIET_DAYS = 3
SCAR_HEAD = 10
SCARS = "memory/scars/"
DATE = re.compile(r"(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)")
TRIGGER = re.compile(r"^\s*trigger:\s*(.*)$", re.IGNORECASE)


def die(why: str, code: int = 2) -> None:
    print(why, file=sys.stderr)
    raise SystemExit(code)


def git(*args: str) -> subprocess.CompletedProcess[bytes]:
    # quotepath off: a non-ASCII path comes back as bytes, not as "caf\303\251".
    return subprocess.run(["git", "-c", "core.quotepath=off", *args], capture_output=True)


def show(rev: str, path: str) -> str | None:
    proc = git("show", f"{rev}:{path}")
    if proc.returncode != 0:
        return None
    return proc.stdout.decode("utf-8", "replace")


def tree(rev: str) -> dict[str, tuple[str, int]]:
    """path -> (blob sha, size) for every regular file under the roots."""
    proc = git("ls-tree", "-r", "-l", "--full-tree", rev, "--", *ROOTS)
    if proc.returncode != 0:
        die(f"git ls-tree {rev}: {proc.stderr.decode('utf-8', 'replace').strip()}")
    files: dict[str, tuple[str, int]] = {}
    for line in proc.stdout.decode("utf-8", "surrogateescape").splitlines():
        meta, _, path = line.partition("\t")
        mode, kind, sha, size = meta.split()
        if kind != "blob" or mode == "120000":
            continue
        if "hearth" in path.split("/"):
            continue
        files[path] = (sha, int(size))
    return files


def blobs(shas: list[str]) -> dict[str, str]:
    """sha -> text, in one cat-file pass."""
    if not shas:
        return {}
    proc = subprocess.run(["git", "cat-file", "--batch"], input="\n".join(shas).encode() + b"\n",
                          capture_output=True)
    if proc.returncode != 0:
        die(f"git cat-file: {proc.stderr.decode('utf-8', 'replace').strip()}")
    out: dict[str, str] = {}
    data = proc.stdout
    pos = 0
    while pos < len(data):
        end = data.index(b"\n", pos)
        header = data[pos:end].decode()
        pos = end + 1
        parts = header.split()
        if len(parts) != 3:
            continue
        sha, size = parts[0], int(parts[2])
        out[sha] = data[pos:pos + size].decode("utf-8", "replace")
        pos += size + 1
    return out


def activity(rev: str) -> tuple[dict[str, int], set[str], int]:
    """Thread -> last author time in its folder; threads written since opened; the newest author time.

    Written since opened: some commit after the one that created the folder touched that
    folder and no other thread's, the way a body lands its own work. A sweep across many
    threads, or a migration, does not wake one."""
    proc = git("log", "--topo-order", "--format=%x00%at", "--name-only", rev, "--", "threads")
    last: dict[str, int] = {}
    commits: list[set[str]] = []
    newest = 0
    if proc.returncode != 0:
        return last, set(), newest
    stamp = 0
    for line in proc.stdout.decode("utf-8", "surrogateescape").splitlines():
        if line.startswith("\x00"):
            stamp = int(line[1:]) if line[1:].isdigit() else 0
            newest = max(newest, stamp)
            commits.append(set())
        elif commits and line.startswith("threads/") and line.count("/") >= 2:
            name = line.split("/")[1]
            last.setdefault(name, stamp)
            commits[-1].add(name)
    oldest = {name: index for index, names in enumerate(commits) for name in names}
    woken = {name for index, names in enumerate(commits) if len(names) == 1
             for name in names if index != oldest[name]}
    return last, woken, newest


def ranks(rev: str) -> dict[str, int]:
    """Path -> position of the commit that last touched it, newest first."""
    proc = git("log", "--topo-order", "--format=%x00", "--name-only", rev, "--", *ROOTS)
    found: dict[str, int] = {}
    if proc.returncode != 0:
        return found
    rank = -1
    for line in proc.stdout.decode("utf-8", "surrogateescape").splitlines():
        if line.startswith("\x00"):
            rank += 1
        elif line and line not in found:
            found[line] = rank
    return found


def split(text: str) -> tuple[dict[str, str], list[str]]:
    """Frontmatter keys as written (lists kept literal) and the lines after it."""
    lines = text.splitlines()
    data: dict[str, str] = {}
    body = lines
    if lines and lines[0] == "---" and "---" in lines[1:]:
        end = lines.index("---", 1)
        for line in lines[1:end]:
            key, sep, raw = line.partition(":")
            if sep and key.strip() and key[:1] not in " \t":
                value = raw.strip()
                if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
                    value = value[1:-1]
                data[key.strip()] = value
        body = lines[end + 1:]
    return data, body


def frontmatter(text: str) -> tuple[dict[str, str], str]:
    """Keys as written and the first non-empty line after the frontmatter."""
    data, body = split(text)
    first = next((line for line in body if line.strip()), "")
    return data, first


def scar_head(text: str) -> tuple[str, str, str]:
    """(title, trigger words, date) of a scar, read from its frontmatter and first SCAR_HEAD non-blank lines."""
    data, body = split(text)
    head = [line for line in body if line.strip()][:SCAR_HEAD]
    trigger = data.get("trigger", "")
    if not trigger:
        for line in head[1:]:
            found = TRIGGER.match(line)
            if found:
                trigger = found.group(1).strip()
                break
    date = next((found.group(0) for found in map(DATE.search, [*data.values(), *head]) if found), "")
    return title(head[0] if head else ""), " ".join(trigger.split()), date


def scar_folders(files: dict[str, tuple[str, int]]) -> dict[str, list[str]]:
    """memory/scars/<domain> -> its scar paths (every .md under it but index.md)."""
    folders: dict[str, list[str]] = {}
    for path in files:
        parts = path.split("/")
        if path.startswith(SCARS) and len(parts) >= 4 and path.endswith(".md") and parts[-1] != "index.md":
            folders.setdefault("/".join(parts[:3]), []).append(path)
    return folders


def scar_indexes(files: dict[str, tuple[str, int]], text: dict[str, str]) -> dict[str, str]:
    """memory/scars/<domain>/index.md -> its generated text, for every folder that holds scars."""
    out: dict[str, str] = {}
    for folder, paths in sorted(scar_folders(files).items()):
        rows: list[tuple[str, str, str]] = []
        for path in paths:
            name, trigger, date = scar_head(text[files[path][0]])
            rel = path[len(folder) + 1:]
            row = " · ".join(part for part in (f"[{rel}]({rel})", name, trigger, date) if part)
            rows.append((date, rel, f"- {row}\n"))
        rows.sort(key=lambda row: row[1])
        rows.sort(key=lambda row: row[0], reverse=True)  # newest first, undated last; stable on the slug
        domain = folder[len(SCARS):]
        up = "../" * (folder.count("/") + 1)  # memory/scars/<domain>/index.md sits three folders down
        head = (f"# Scars: {domain} ({len(rows)})\n\n"
                "Generated by `core/loom/index` at every landing: do not edit. "
                f"One row per scar, newest first: title · trigger words · date. "
                f"Read a scar before the act its trigger names; the rule is in [AGENTS.md]({up}AGENTS.md).\n\n")
        out[f"{folder}/index.md"] = head + "".join(row[2] for row in rows)
    return out


def title(first: str) -> str:
    text = first[2:] if first.startswith("# ") else first
    text = " ".join(text.split())
    return text if len(text) <= HEADLINE else text[:HEADLINE - 1] + "…"


def kb(size: int) -> str:
    return "<1 KB" if size < 1024 else f"{size // 1024} KB"


def wish_lines(data: dict[str, str]) -> str:
    ids = data.get("opened-for", "")
    ids = [part.strip().strip('"') for part in ids.strip("[]").split(",") if part.strip()]
    parts = []
    for ident in ids:
        line = data.get(f"wish-{ident}", "")
        parts.append(f"{ident} {line}".strip())
    return "; ".join(parts)


def topic_rows(files: dict[str, tuple[str, int]], text: dict[str, str]) -> str:
    pages = sorted(path for path in files
                   if path.startswith("topics/") and path.count("/") == 1 and path.endswith(".md")
                   and path != "topics/README.md")
    if not pages:
        return ""
    out = [f"## topics ({len(pages)})\n\n"]
    if "topics/README.md" in files:
        out.append("What was decided and why, one page per area; the shape is in "
                   "[topics/README.md](topics/README.md).\n\n")
    for path in pages:
        sha, size = files[path]
        _, first = frontmatter(text[sha])
        entries = sum(1 for line in text[sha].splitlines() if line.startswith("### "))
        out.append(f"- **[{path[7:-3]}]({path})** · {title(first)} · {entries} entr{'y' if entries == 1 else 'ies'} · {kb(size)}\n")
    return "".join(out) + "\n"


def thread_rows(files: dict[str, tuple[str, int]], text: dict[str, str], order: dict[str, int],
                seen: tuple[dict[str, int], set[str], int] = ({}, set(), 0)) -> str:
    threads: dict[str, list[str]] = {}
    for path in files:
        parts = path.split("/")
        if parts[0] == "threads" and len(parts) >= 3 and path.endswith(".md"):
            threads.setdefault(parts[1], []).append(path)
    rows: list[tuple[int, int, str, str]] = []
    for name, paths in threads.items():
        readme = f"threads/{name}/README.md"
        data, first = frontmatter(text[files[readme][0]]) if readme in files else ({}, "")
        status = data.get("status", "")
        head = f"- **[{name}]({readme})**" if readme in files else f"- **{name}**"
        head += f" · {status or 'no README'}"
        last, woken, newest = seen
        group = 3
        if status in OPEN or not status:
            days = max(0, newest - last.get(name, newest)) // 86400
            group = 2 if name not in woken else 1 if days >= QUIET_DAYS else 0
            if group == 1:
                head += f" · quiet {days}d"
        wishes = wish_lines(data)
        if wishes:
            head += f" · {wishes}"
        if first and not any(data.get(key) for key in data if key.startswith("wish-")):
            head += f" · {title(first)}"
        lines = [head]
        for path in sorted(paths):
            if path == readme:
                continue
            sha, size = files[path]
            rel = path[len(f"threads/{name}/"):]
            _, line = frontmatter(text[sha])
            lines.append(f"  - [{rel}]({path}) · {title(line)} · {kb(size)}")
        rank = min(order.get(path, 10**9) for path in paths)
        rows.append((group, rank, name, "\n".join(lines)))
    rows.sort(key=lambda row: (row[0], row[1], row[2]))
    out = ["## threads\n"]
    for label, group in (("open, moving", 0), ("open, quiet", 1), ("open, untouched since opened", 2), ("settled", 3)):
        chosen = [row for row in rows if row[0] == group]
        out.append(f"\n### {label} ({len(chosen)})\n\n")
        out.extend(row[3] + "\n" for row in chosen)
    return "".join(out)


def memory_rows(files: dict[str, tuple[str, int]], text: dict[str, str]) -> str:
    out = ["\n## memory\n\n"]
    folders: dict[str, int] = {}
    singles: list[tuple[str, str]] = []
    for path in sorted(files):
        parts = path.split("/")
        if parts[0] != "memory" or not path.endswith(".md"):
            continue
        if parts[1] == "scars" and len(parts) >= 4:
            folders[parts[2]] = folders.get(parts[2], 0) + (0 if parts[-1] == "index.md" else 1)
            continue
        sha, size = files[path]
        _, first = frontmatter(text[sha])
        singles.append((path, f"- [{path[7:]}]({path}) · {title(first)} · {kb(size)}"))
    for name, count in sorted(folders.items()):
        # The folder index is derived by --write in the same pass (and removed where no
        # scar is left), so the row links it whether or not this tree has it yet and a
        # folder holding only an index gets no row: the row must not flip at the landing.
        if count:
            singles.append((f"memory/scars/{name}", f"- [scars/{name}/](memory/scars/{name}/index.md) · {count} scars"))
    singles.sort()
    out.extend(line + "\n" for _, line in singles)
    return "".join(out)


def people_rows(files: dict[str, tuple[str, int]]) -> str:
    names = sorted({path.split("/")[1] for path in files if path.startswith("people/") and path.count("/") >= 2})
    return "\n## people\n\n" + "".join(f"- {name}\n" for name in names)


def load(rev: str) -> tuple[dict[str, tuple[str, int]], dict[str, str]]:
    files = tree(rev)
    text = blobs(sorted({sha for path, (sha, _) in files.items() if path.endswith(".md")}))
    return files, text


def generate(rev: str, loaded: tuple[dict[str, tuple[str, int]], dict[str, str]] | None = None) -> str:
    files, text = loaded if loaded is not None else load(rev)
    order = ranks(rev)
    head = ("# Index\n\n"
            "Generated by `core/loom/index` at every landing: do not edit. "
            "Read [AGENTS.md](AGENTS.md) first. Topic pages first, then one row per thread, open first (moving, quiet, untouched since opened), newest first; "
            "under it, the thread's files with their first line and size.\n\n")
    return head + topic_rows(files, text) + thread_rows(files, text, order, activity(rev)) + memory_rows(files, text) + people_rows(files)


def check_scars(rev: str, old: str | None, loaded: tuple[dict[str, tuple[str, int]], dict[str, str]]) -> int:
    """Each scar folder's index.md at REV is what its scars derive; none is left where no scar is."""
    status = 0
    files, text = loaded
    expected = scar_indexes(files, text)
    legacy: set[str] = set()
    if old is not None:
        before = tree(old)
        legacy = {folder for folder in scar_folders(before) if f"{folder}/index.md" not in before}
    for path, want in expected.items():
        have = text.get(files[path][0]) if path in files else None
        if have is None:
            if path[:-len("/index.md")] in legacy:
                continue
            print(f"{path}: missing; run core/loom/index --write and commit", file=sys.stderr)
            status = 1
        elif have != want:
            print(f"{path}: differs from core/loom/index at {rev}; run core/loom/index --write and commit",
                  file=sys.stderr)
            status = 1
    for path in sorted(files):
        if path.startswith(SCARS) and path.endswith("/index.md") and path.count("/") == 3 and path not in expected:
            print(f"{path}: no scars beside it; run core/loom/index --write and commit", file=sys.stderr)
            status = 1
    return status


def check(rev: str, old: str | None) -> int:
    status = 0
    was = (lambda path: old is not None and show(old, path) is not None)
    loaded = load(rev)
    current = show(rev, "INDEX.md")
    if current is None:
        if was("INDEX.md"):
            print("INDEX.md: deleted; run core/loom/index --write and commit", file=sys.stderr)
            status = 1
    elif current != generate(rev, loaded):
        print(f"INDEX.md: differs from core/loom/index at {rev}; run core/loom/index --write and commit",
              file=sys.stderr)
        status = 1
    agents = show(rev, "AGENTS.md")
    claude = show(rev, "CLAUDE.md")
    if claude is None:
        if was("CLAUDE.md"):
            print("CLAUDE.md: deleted; run core/loom/index --write and commit", file=sys.stderr)
            status = 1
    elif agents is None:
        print("CLAUDE.md: present without AGENTS.md; run core/loom/index --write and commit", file=sys.stderr)
        status = 1
    elif claude != agents:
        print("CLAUDE.md: not a copy of AGENTS.md; run core/loom/index --write and commit", file=sys.stderr)
        status = 1
    return status | check_scars(rev, old, loaded)


def write(rev: str) -> None:
    root = Path.cwd()
    loaded = load(rev)
    (root / "INDEX.md").write_text(generate(rev, loaded), encoding="utf-8")
    agents = show(rev, "AGENTS.md")
    claude = root / "CLAUDE.md"
    if agents is None:
        claude.unlink(missing_ok=True)
    else:
        claude.write_text(agents, encoding="utf-8")
    indexes = scar_indexes(*loaded)
    for path, body in indexes.items():
        target = root / path
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(body, encoding="utf-8")
    for stale in root.glob("memory/scars/*/index.md"):
        if stale.relative_to(root).as_posix() not in indexes:
            stale.unlink()


def main(argv: list[str]) -> int:
    rev = "HEAD"
    old = None
    mode = "print"
    args = list(argv)
    while args:
        arg = args.pop(0)
        if arg == "--rev" and args:
            rev = args.pop(0)
        elif arg == "--old" and args:
            old = args.pop(0)
        elif arg in ("--write", "--check"):
            mode = arg[2:]
        else:
            die("usage: core/loom/index [--rev REV] [--write | --check [--old REV]]")
    if old is not None and all(char == "0" for char in old):
        old = None
    if mode == "check":
        return check(rev, old)
    if mode == "write":
        write(rev)
        return 0
    sys.stdout.write(generate(rev))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
