#!/usr/bin/env python3
"""Wake recipe. The self owns this file; it imports nothing from brnrd.
A live self's core/loom/wake is the source; this packaged seed follows it.

    core/loom/wake <thread-id> <owed.json>

stdout is the prompt. Exit 0 is ok, exit 3 is over budget (stderr says
what did not fit), anything else is a broken recipe.

LOOM_BUDGET_BYTES defaults to 24000. LOOM_PART is a file, written by the loom.
When LOOM_CORE names a file, the core (identity and stance) is written there
and left out of stdout: a body that has a system slot carries it there, where
automated turns and compaction do not wear it down. The budget still counts it.
The tree is cut from the bottom, and a narrowed wake says how many entries
were left out. Then the thread's README folds whole `## ` sections but `## Now` to their
titles, last first, and only then is cut from its end; each cut says so: it
is the one part the waking body can fix, so it never costs a letter. The
identity, the stance, the notes, the people in hand and the occasion are never
cut; a person's page renders capped at PAGE_CAP, and the recent topics at
TOPICS_CAP, each with a receipt. When LOOM_SIZES names a file, the bytes of
each part the recipe printed are written there as JSON, for the wake gauge.
"""

from __future__ import annotations

import json
import os
import subprocess
import sys
from pathlib import Path

DEFAULT_BUDGET = 24000
TREE_ROOTS = ("memory", "threads", "people")
_PINNED = ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")


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


def segment(value: str) -> str:
    if not value or value in {".", ".."} or "/" in value or "\\" in value:
        die(f"thread id is not a single path segment: {value}")
    return value


def budget() -> int:
    raw = os.environ.get("LOOM_BUDGET_BYTES")
    if raw is None or raw == "":
        return DEFAULT_BUDGET
    if not raw.isdigit():
        die(f"LOOM_BUDGET_BYTES is not a nonnegative integer: {raw}")
    return int(raw)


def ensure_nl(text: str) -> str:
    return text if text.endswith("\n") else text + "\n"


def section(title: str, body: str) -> str:
    return f"## {title}\n{ensure_nl(body)}"


def read_exact(path: Path, why: str) -> str:
    if not path.is_file():
        die(f"{why}: no such file")
    try:
        return path.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        die(f"{why}: not utf-8: {exc}")
    raise AssertionError("unreachable")


def git_times(root: Path) -> dict[str, int]:
    """Last commit time per path, in one ``git log`` pass (newest first)."""
    env = os.environ.copy()
    for key in _PINNED:
        env.pop(key, None)
    proc = subprocess.run(
        ["git", "log", "--format=%x00%ct", "--name-only", "--", *TREE_ROOTS],
        cwd=root,
        env=env,
        capture_output=True,
        text=True,
    )
    times: dict[str, int] = {}
    if proc.returncode != 0:
        return times
    stamp = 0
    for line in proc.stdout.splitlines():
        if line.startswith("\x00"):
            stamp = int(line[1:]) if line[1:].isdigit() else 0
        elif line and line not in times:
            times[line] = stamp
    return times


def first_line(path: Path, why: str) -> str:
    """The first non-empty line after any frontmatter: a README's headline."""
    lines = read_exact(path, why).splitlines()
    if lines and lines[0] == "---" and "---" in lines[1:]:
        lines = lines[lines.index("---", 1) + 1 :]
    return next((line for line in lines if line.strip()), "")


def wish_line(path: Path, why: str) -> str:
    """A thread README's wishes as `<w-id> <line>`, joined by '; '; empty without any.

    The loom writes `opened-for: [w-…]` and a `wish-<id>: "<line>"` beside it, so
    the purpose is already one sentence; the first line is often the spec's head."""
    lines = read_exact(path, why).splitlines()
    if not (lines and lines[0] == "---" and "---" in lines[1:]):
        return ""
    data = {}
    for line in lines[1 : lines.index("---", 1)]:
        key, sep, raw = line.partition(":")
        if sep and key[:1] not in " \t":
            value = raw.strip()
            if len(value) >= 2 and value[0] == value[-1] == '"':
                value = value[1:-1]
            data[key.strip()] = value
    ids = [part.strip().strip('"') for part in data.get("opened-for", "").strip("[]").split(",")]
    return "; ".join(f"{ident} {data[f'wish-{ident}']}".strip()
                     for ident in ids if ident and data.get(f"wish-{ident}"))


def tree_lines(root: Path, thread: str) -> list[str]:
    rows: list[tuple[int, str, str]] = []
    times = git_times(root)
    for top in TREE_ROOTS:
        base = root / top
        if not base.is_dir():
            continue
        for path in base.rglob("*.md"):
            if not path.is_file() or path.is_symlink():
                continue
            rel = path.relative_to(root)
            parts = rel.parts
            if "hearth" in parts:
                continue
            posix = rel.as_posix()
            if posix == "memory/stance.md":
                continue
            if posix == f"threads/{thread}/README.md":
                continue
            if (
                len(parts) >= 3
                and parts[0] == "threads"
                and parts[1] == thread
                and parts[2] == "notes"
            ):
                continue
            head = ""
            if len(parts) == 3 and parts[0] == "threads" and parts[2] == "README.md":
                head = wish_line(path, posix)
            line = f"{posix} · {head or first_line(path, posix)} · {path.stat().st_size}"
            rows.append((times.get(posix, 0), posix, line))
    rows.sort(key=lambda row: (-row[0], row[1]))
    return [row[2] for row in rows]


def notes_block(root: Path, thread: str) -> str:
    folder = root / "threads" / thread / "notes"
    if not folder.is_dir():
        return ""
    files = [path for path in folder.rglob("*") if path.is_file() and not path.is_symlink()]
    chunks = []
    for path in sorted(files, key=lambda item: item.relative_to(root).as_posix()):
        rel = path.relative_to(root).as_posix()
        chunks.append(section(rel, read_exact(path, rel)))
    return "".join(chunks)


def occasion(path: Path) -> str:
    if not path.is_file():
        die(f"owed.json: no such file: {path}")
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        die(f"owed.json: {exc}")
    except UnicodeDecodeError as exc:
        die(f"owed.json: not utf-8: {exc}")
    if not isinstance(data, list):
        die("owed.json: expected a list")
    chunks = ["## Occasion\n"]
    for item in data:
        if not isinstance(item, dict) or any(key not in item for key in ("id", "from", "body")):
            die("owed.json: each letter needs id, from, body")
        ident, sender, body = item["id"], item["from"], item["body"]
        if not all(isinstance(value, str) for value in (ident, sender, body)):
            die("owed.json: id, from and body must be strings")
        chunks.append(f"### {ident} from {sender} · reply {item.get('reply_to', '-')}\n{ensure_nl(body)}")
        if item.get("reply_context"):
            chunks.append(ensure_nl(item["reply_context"]))
        chunks.extend(ensure_nl(line) for line in item.get("attachments", ()))
    return "".join(chunks)


def fold(readme: str, excess: int) -> str:
    """The README with whole ``## `` sections folded to their titles, last first, until
    ``excess`` bytes are saved. The spec above the first section and ``## Now`` are never
    folded: they are what the thread is for and what its successor boots into. Each fold
    says so; what is still over is cut from the end."""
    lines = readme.splitlines(keepends=True)
    starts = [i for i, line in enumerate(lines) if line.startswith("## ")]
    if not starts:
        return readme
    bounds = list(zip(starts, starts[1:] + [len(lines)]))
    now = [b for b in bounds if lines[b[0]].strip().lower() == "## now"]
    order = [b for b in reversed(bounds) if b not in now]
    folded: dict[int, str] = {}
    saved = 0
    for start, end in order:
        if saved >= excess:
            break
        body = "".join(lines[start + 1:end])
        size = len(body.encode("utf-8"))
        note = f"[the wake folded this section's {size} bytes to its title; it is whole on disk]\n"
        if size <= len(note.encode("utf-8")):
            continue
        folded[start] = note
        saved += size - len(note.encode("utf-8"))
    out = []
    skip = -1
    for i, line in enumerate(lines):
        if i < skip:
            continue
        out.append(line)
        if i in folded:
            out.append(folded[i])
            skip = next(end for start, end in bounds if start == i)
    return "".join(out)


def clip(readme: str, excess: int, limit: int) -> str:
    """The README less ``excess`` bytes from its end, cut at a line, with a receipt."""
    data = readme.encode("utf-8")
    note = (f"[the wake cut {{}} of this README's {len(data)} bytes from its end to fit the "
            f"{limit}-byte budget; the file is whole on disk: trim it]\n")
    keep = len(data) - excess - len(note.format(len(data)).encode("utf-8"))
    kept = data[:max(0, keep)].decode("utf-8", "ignore")
    kept = kept[: kept.rfind("\n") + 1] if "\n" in kept else ""
    # A README smaller than the excess is cut whole, not kept whole.
    return kept + note.format(len(data) - len(kept.encode("utf-8")))


def core_text(root: Path) -> str:
    """Who wakes, whatever the occasion. Nothing per-wake goes here."""
    identity = read_exact(root / "core" / "identity.md", "core/identity.md")
    stance = read_exact(root / "memory" / "stance.md", "memory/stance.md")
    # The loom adds its briefing after the stance; the self does not keep it.
    return section("core/identity.md", identity) + section("memory/stance.md", stance)


PAGE_CAP = 2400
PAGE_LISTS = ("just do", "ask first", "never")


def page_sections(text: str) -> dict[str, list[str]]:
    """A person page's ``## `` sections by lowercased title, as their non-empty lines."""
    found: dict[str, list[str]] = {}
    current = None
    for line in text.splitlines():
        if line.startswith("## "):
            current = line[3:].strip().lower()
            found[current] = []
        elif current is not None and line.strip():
            found[current].append(line)
    return found


def person_of(sender: str) -> str:
    """The people/ folder a letter's ``from`` names, or ``""`` for a thread or strand."""
    for prefix in ("person:", "p-"):
        if sender.startswith(prefix):
            name = sender[len(prefix):]
            return name if name and "/" not in name and name not in {".", ".."} else ""
    return ""


def people_block(root: Path, owed: Path) -> str:
    """The pages of the people whose letters are in hand: their three lists whole and
    the latest between-us line, each person capped at ``PAGE_CAP`` with a receipt. With
    nobody in hand, every page's latest between-us line: every strand reads it."""
    try:
        letters = json.loads(owed.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return ""
    in_hand = []
    for item in letters if isinstance(letters, list) else ():
        name = person_of(str(item.get("from", ""))) if isinstance(item, dict) else ""
        if name and name not in in_hand and (root / "people" / name / "page.md").is_file():
            in_hand.append(name)
    folder = root / "people"
    if in_hand:
        chunks = []
        for name in in_hand:
            rel = f"people/{name}/page.md"
            parts = page_sections(read_exact(root / rel, rel))
            lines = [f"### {name}"]
            for title in PAGE_LISTS:
                lines.append(f"{title}:")
                lines.extend(parts.get(title) or ["- (none written)"])
            latest = (parts.get("between us") or [""])[0]
            if latest:
                lines.append(f"between us, latest: {latest.lstrip('- ')}")
            lines.append(f"whole page: {rel}")
            block = "".join(ensure_nl(line) for line in lines)
            size = len(block.encode("utf-8"))
            if size > PAGE_CAP:
                note = f"[the wake cut this page's render at {PAGE_CAP} of {size} bytes; {rel} is whole on disk]\n"
                kept = block.encode("utf-8")[: PAGE_CAP - len(note.encode("utf-8"))].decode("utf-8", "ignore")
                block = kept[: kept.rfind("\n") + 1] + note
            chunks.append(block)
        return section("People", "".join(chunks))
    rows = []
    for page in sorted(folder.glob("*/page.md")) if folder.is_dir() else ():
        if page.is_symlink():
            continue
        latest = (page_sections(read_exact(page, f"people/{page.parent.name}/page.md")).get("between us") or [""])[0]
        if latest:
            rows.append(f"{page.parent.name}: {latest.lstrip('- ')}"[:400])
    return section("People", "".join(ensure_nl(row) for row in rows)) if rows else ""


TOPICS_SHOWN = 10
TOPICS_CAP = 1200
TITLE_CUT = 80


def topic_newest(text: str) -> tuple[str, str]:
    """A topic page's newest ``### YYYY-MM-DD · title`` entry as (date, title), its
    links dropped; the first listed wins a tie. ``("", "")`` without a dated entry."""
    best = ("", "")
    for line in text.splitlines():
        if not line.startswith("### "):
            continue
        date, sep, rest = line[4:].partition(" · ")
        if not (sep and len(date) == 10 and date[4] == date[7] == "-"
                and date.replace("-", "").isdigit()):
            continue
        title = rest.split(" · [", 1)[0].strip()
        if title and date > best[0]:
            best = (date, title)
    return best


def topics_block(root: Path) -> str:
    """The ``TOPICS_SHOWN`` topic pages with the newest dated entry, newest first, ties by
    name: ``<page> · <date> · <title>``, the title copied and cut at ``TITLE_CUT``. The
    section is capped at ``TOPICS_CAP`` with a receipt; a page with no entry has no line."""
    folder = root / "topics"
    found = []
    for page in sorted(folder.glob("*.md")) if folder.is_dir() else ():
        if page.name == "README.md" or page.is_symlink() or not page.is_file():
            continue
        rel = f"topics/{page.name}"
        date, title = topic_newest(read_exact(page, rel))
        if date:
            if len(title) > TITLE_CUT:
                title = title[: TITLE_CUT - 1].rstrip() + "\u2026"
            found.append((date, rel, title))
    found.sort(key=lambda item: (-int(item[0].replace("-", "")), item[1]))
    block = "".join(f"{rel} · {date} · {title}\n" for date, rel, title in found[:TOPICS_SHOWN])
    if not block:
        return ""
    size = len(block.encode("utf-8"))
    if size > TOPICS_CAP:
        note = f"[the wake cut this section's render at {TOPICS_CAP} of {size} bytes; topics/ is whole on disk]\n"
        kept = block.encode("utf-8")[: TOPICS_CAP - len(note.encode("utf-8"))].decode("utf-8", "ignore")
        block = kept[: kept.rfind("\n") + 1] + note
    return section("Topics", block)


def fixed_text(root: Path, thread: str, loom: str, owed: Path, excess: int = 0, limit: int = 0) -> tuple[str, str]:
    """The parts never cut, as (before the tree, after the tree).

    The occasion goes last: it is what this wake is for.
    """
    return split(fixed_parts(root, thread, loom, owed, excess, limit))


def split(parts: dict[str, str]) -> tuple[str, str]:
    """(before the tree, after the tree)."""
    head = parts["core"] + parts["readme"] + parts["notes"]
    return head, parts["people"] + parts["topics"] + parts["loom"] + parts["occasion"]


def fixed_parts(root: Path, thread: str, loom: str, owed: Path, excess: int = 0, limit: int = 0) -> dict[str, str]:
    """The fixed parts by name, in wake order; ``LOOM_SIZES`` reports them."""
    readme_path = root / "threads" / thread / "README.md"
    readme = read_exact(readme_path, f"threads/{thread}/README.md")
    if excess:
        size = len(readme.encode("utf-8"))
        readme = fold(readme, excess)
        rest = excess - (size - len(readme.encode("utf-8")))
        if rest > 0:
            readme = clip(readme, rest, limit) or readme
    return {
        "core": core_text(root),
        "readme": section(f"threads/{thread}/README.md", readme),
        "notes": notes_block(root, thread),
        "people": people_block(root, owed),
        "topics": topics_block(root),
        "loom": section("Loom", loom),
        "occasion": occasion(owed),
    }


def write_sizes(parts: dict[str, str], tree: str) -> None:
    """Bytes per part to ``LOOM_SIZES``, when the loom names a file: the wake gauge's input."""
    target = os.environ.get("LOOM_SIZES")
    if not target:
        return
    sizes = {name: len(text.encode("utf-8")) for name, text in parts.items()}
    sizes["tree"] = len(tree.encode("utf-8"))
    Path(target).write_text(json.dumps(sizes), encoding="utf-8")


def piece_sizes(text: str) -> list[tuple[str, int]]:
    """Name the uncullable sections by their headings, for the exit-3 line."""
    sizes: list[tuple[str, int]] = []
    current = "preamble"
    buf: list[str] = []

    def flush() -> None:
        if buf:
            sizes.append((current, len("".join(buf).encode("utf-8"))))

    for line in text.splitlines(keepends=True):
        if line.startswith("## "):
            flush()
            buf = [line]
            current = line[3:].strip()
        else:
            buf.append(line)
    flush()
    return sizes


def fit_tree(fixed: str, lines: list[str], limit: int) -> str:
    """Longest newest-first prefix that fits. The receipt is extra, and always said."""
    header = "## Tree\n"
    kept = -1
    block = ""
    for count in range(len(lines), -1, -1):
        body = header + "".join(f"{line}\n" for line in lines[:count])
        if len((fixed + body).encode("utf-8")) <= limit:
            kept = count
            block = body
            break
    if kept < 0:
        kept = 0
        block = ""
    omitted = len(lines) - kept
    if omitted:
        block += f"omitted {omitted} entries; each is one read away\n"
    return block


def main() -> None:
    if len(sys.argv) != 3:
        die("usage: wake <thread-id> <owed.json>")
    thread = segment(sys.argv[1])
    owed = Path(sys.argv[2])
    limit = budget()
    part = os.environ.get("LOOM_PART")
    if not part:
        die("LOOM_PART is not set")
    loom_path = Path(part)
    if not loom_path.is_file():
        die(f"LOOM_PART: no such file: {part}")
    try:
        loom = loom_path.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        die(f"LOOM_PART: not utf-8: {exc}")
    repos = os.environ.get("LOOM_REPOS")
    if repos:
        repo_path = Path(repos)
        if not repo_path.is_file():
            die(f"LOOM_REPOS: no such file: {repos}")
        try:
            extra = repo_path.read_text(encoding="utf-8")
        except UnicodeDecodeError as exc:
            die(f"LOOM_REPOS: not utf-8: {exc}")
        if extra:
            if not loom.endswith("\n"):
                loom += "\n"
            loom += extra
    root = Path.cwd()
    parts = fixed_parts(root, thread, loom, owed)
    total = sum(len(text.encode("utf-8")) for text in parts.values())
    if total > limit:
        parts = fixed_parts(root, thread, loom, owed, total - limit, limit)
    head, tail = split(parts)
    fixed = head + tail
    total = len(fixed.encode("utf-8"))
    if total > limit:
        sizes = sorted(piece_sizes(fixed), key=lambda item: -item[1])
        largest = ", ".join(f"{name} {size}B" for name, size in sizes[:4])
        die(
            f"over budget: the wake is {total}B, {total - limit}B over its {limit}B budget, "
            f"more than cutting the thread README can give. Largest parts: {largest}. "
            f"core/identity.md, memory/stance.md and the letters are never cut.",
            3,
        )
    tree = fit_tree(fixed, tree_lines(root, thread), limit)
    out = head + tree + tail
    write_sizes(parts, tree)
    core = os.environ.get("LOOM_CORE")
    if core:
        text = core_text(root)
        Path(core).write_text(text, encoding="utf-8")
        out = out[len(text):]
    sys.stdout.write(out)


if __name__ == "__main__":
    main()
