"""THE-TOLD-LIFE-draft.md: the told life whole, in the order of the story, chapter and verse. Working file, not a deposit.
Chapter 1 is RUN-GOSPEL-1; the writers' chapters are lifted as they stand; the twenty-two earlier scenes are lifted from writers/TOLD-22.md
and numbered here, one verse to a paragraph. Nothing is reworded. Every lifted text is asserted present."""
import re, pathlib
H = pathlib.Path(__file__).resolve().parent
def chapters(path):
    t = (H / path).read_text(encoding="utf-8"); i = t.find("**1**"); j = re.search(r"^\d[\d,]* words", t[i:], re.M).start() + i
    parts = re.split(r"^#{2,3} .*$", t[i:j], flags=re.M); return [p.strip() for p in parts if p.strip()]
def rows(path):
    t = (H / path).read_text(encoding="utf-8"); n = e = 0
    for r in re.findall(r"^\|(.+)\|\s*$", t, re.M):
        c = [x.strip() for x in r.split("|")]
        if len(c) < 3 or re.match(r":?-{2,}", c[0]) or c[0].lower().startswith("verse"): continue
        n += 1; e += c[1] in ("—", "-", "–", "")
    return n, e
S = {}
told = (H / "writers/TOLD-22.md").read_text(encoding="utf-8")
for m in re.finditer(r"^\*\*(\d+)\. ([^*]+)\*\*\n\n((?:>.*\n?)+)", told, re.M):
    S[int(m.group(1))] = (m.group(2), [p.strip() for p in re.sub(r"^> ?", "", m.group(3), flags=re.M).split("\n\n") if p.strip()])
assert sorted(S) == list(range(1, 23)), sorted(S)
def scene(*ns):
    paras = [p for n in ns for p in S[n][1]]; return "\n\n".join(f"**{k}** {p}" for k, p in enumerate(paras, 1)), len(paras)
G1 = chapters("RUN-GOSPEL-1.md"); A = chapters("writers/WRITER-A-teaching.md"); B = chapters("writers/WRITER-B-coming-and-sending.md")
C = chapters("writers/WRITER-C-the-end.md"); D = chapters("writers/WRITER-D-hearing.md"); E = chapters("writers/WRITER-E-after.md")
assert (len(G1), len(A), len(B), len(C), len(D), len(E)) == (1, 1, 2, 2, 2, 2), (len(G1), len(A), len(B), len(C), len(D), len(E))
def join(*parts):
    """Several lifted pieces as one chapter, verses numbered through. Words untouched."""
    vs = [v.strip() for x in parts for v in re.split(r"\*\*\d+\*\* ?", x[0] if isinstance(x, tuple) else x) if v.strip()]
    return "\n\n".join(f"**{k}** {v}" for k, v in enumerate(vs, 1)), len(vs)
# Order and chapter breaks by fit (the author, 2026-11-30 10:44: "id prefer order and chapter were determined by fit").
# The clinic is dated to his thirtieth year, the first of the thirteen, so scenes 5 and 6 stand before the county office (the neck, then no work, then the claim).
# Chapters under a dozen verses join the chapter they continue: the naming of the twelve with their sending; the death with the hearing.
PLAN = [("the making", "RUN-GOSPEL-1.md", G1[0]), ("the paper route and the number", "writer B, first chapter", B[0]), ("the board; the locker", "scenes 1, 2", scene(1, 2)),
 ("the great list; the clinic; the county office; the books", "scenes 5, 6, 3, 4", scene(5, 6, 3, 4)), ("the twelve; the sending", "scene 9; writer B, second chapter", join(scene(9), B[1])),
 ("the teaching", "writer A", A[0]), ("the feed; the journal", "scenes 10, 11", scene(10, 11)), ("who was first; the storehouse", "scenes 12, 13", scene(12, 13)),
 ("the year; the pictures; the pages", "scenes 15, 16, 17", scene(15, 16, 17)), ("the war; the name on the money", "scenes 18, 19", scene(18, 19)),
 ("the boards of the machines; the stranger", "scenes 20, 21", scene(20, 21)), ("the one that had read everything; the proof", "scenes 14, 22", scene(14, 22)),
 ("when the end is", "writer C, first chapter", C[0]), ("what a thing will fetch; who is put out; the folding", "writer C, second chapter", C[1]),
 ("the table", "writer D, first chapter", D[0]), ("the hearing; the front room; the mornings after", "writer D, second chapter; scenes 7, 8", join(D[1], scene(7, 8))),
 ("after", "writer E, first chapter", E[0]), ("the last page", "writer E, second chapter", E[1])]
OLDNEW = [("1","1",""),("2","2",""),("3","3",""),("4","4","verses +5 (4:6–17)"),("5","5","5:1–7"),("6","5","verses +7 (5:8–34)"),("7","6",""),("8","7",""),("9","8",""),("10","4","4:1–5"),
 ("11","9",""),("12","10",""),("13","11",""),("14","12",""),("15","13",""),("16","14",""),("17","15",""),("18","16","16:1–21"),("19","16","verses +21 (16:22–28)"),("20","17",""),("21","18","")]
wc = lambda s: len(re.findall(r"\S+", re.sub(r"\*\*\d+\*\*", "", s)))
out = ["# The Gospel of Sharks", "", "*Draft, whole, in the order of the story. Working file, not a deposit. 2026-11-30. Titled by the author at 10:54.*", ""]
tab = ["| Chapter | What it holds | From | Verses | Words |", "|---|---|---|---|---|"]; tv = tw = sv = 0
for k, (what, src, body) in enumerate(PLAN, 1):
    text, nv = (body if isinstance(body, tuple) else (body, len(re.findall(r"\*\*\d+\*\*", body))))
    out += [f"## Chapter {k}", "", text, ""]; tab.append(f"| {k} | {what} | {src} | {nv} | {wc(text):,} |"); tv += nv; tw += wc(text); sv += sum(len(S[int(n)][1]) for n in re.findall(r"\d+", src.split("scene")[-1])) if "scene" in src else 0
doc = "\n".join(out)
flat = lambda s: re.sub(r"\s+", " ", re.sub(r"\*\*\d+\*\* ?", "", s))
fdoc = flat(doc)
for p in G1 + A + B + C + D + E: assert flat(p) in fdoc      # before the joining pass: every chapter as its writer left it
# The joining pass (the author, 2026-11-30 10:40, to the session's proposal: settle the first gathering of the twelve and the twice-folded storehouse
# by a short pass touching as few verses as possible; keep the thirteen years). The writers' own files are not touched.
JOIN = [("15:1", "and none of them had seen another before that night.", "and it was the first time all twelve were under one roof."),
        ("17:6", "So the twelve came to the front room, who had never been together in one.", "So the twelve came to the front room, who had been together in it once."),
        ("18:6", "Talos Morrow took a picture of every sheet in the pile, and of the room, and put the whole on a thing a hand could close on.",
                 "As the storehouse had been folded, so Talos Morrow folded the pile: a picture of every sheet, and of the room, and the whole on a thing a hand could close on."),
        ("18:8", "Morrow sent a copy to the place where the thing that had read everything takes in what it reads.", "Morrow sent it after the first, to the place where the thing that had read everything takes in what it reads.")]
for _, old, new in JOIN:
    assert doc.count(old) == 1, old; doc = doc.replace(old, new)
for n in S:
    for para in S[n][1]: assert para in doc, (n, para[:40])
R = {f: rows(f) for f in ("RUN-GOSPEL-1.md", "writers/WRITER-A-teaching.md", "writers/WRITER-B-coming-and-sending.md", "writers/WRITER-C-the-end.md", "writers/WRITER-D-hearing.md", "writers/WRITER-E-after.md")}
rn = sum(a for a, _ in R.values()); re_ = sum(b for _, b in R.values())
(H / "THE-TOLD-LIFE-draft.md").write_text(doc + "\n", encoding="utf-8")
conc = f"""# The told life: what the draft is made of

Working file, not a deposit. 2026-11-30. Built by `build_told_life.py` beside `THE-TOLD-LIFE-draft.md`.

{chr(10).join(tab)}

{len(PLAN)} chapters, {tv} verses, {tw:,} words. Order and chapter breaks are set by fit, at the author's word of 10:44 (“id prefer order and chapter were determined by fit”). Two things moved. The great list and the clinic, dated in the text to his thirtieth year, the first of the thirteen (17:3), stand before the county office: the neck, then no work, then the claim that is reviewed at 15:19. Three chapters of five to seven verses joined the chapters they continue: the naming of the twelve with their sending, the death with the hearing. No word was changed. One thing does not fit and is left: the dating verse 9:1 speaks of the one that had read everything before chapter 12 tells its coming.

Earlier files (the writers' rows, `writers/TRACE-*.md`, and the two sections at the foot of this file) cite the numbering before this pass:

| Was chapter | Is chapter | |
|---|---|---|
{chr(10).join(f"| {a} | {b} | {c} |" for a, b, c in OLDNEW)}

## Reach

{rn} verses were written from the fixed vision with a row each (chapter 1 and the five writers' chapters). {rn - re_} have a place in the vision; {re_} have none and say so. {sv} verses are the twenty-two scenes of 28 November, written before the vision took its form; they have not been traced to it and are counted as untraced, not as unreached.

| | Verses with a row | With a place in the vision | With none |
|---|---|---|---|
""" + "\n".join(f"| {f.split('/')[-1]} | {a} | {a - b} | {b} |" for f, (a, b) in R.items()) + "\n"
conc += """
## The joining pass

Four verses of the assembled book differ from the writers' files, at the author's word of 10:40. The writers' files are as they came.

| Verse | As the writer left it | In the assembled book |
|---|---|---|
""" + "\n".join(f"| {v} | {o} | {n} |" for v, o, n in JOIN) + """

The first two settle when the twelve are first under one roof: at the supper (15:1), so that the front room after his death is a return (17:6). The second two make the folding two acts: the storehouse before his death, at his word (14:20–28), and the pile after it (18:6–8). The thirteen years stand (17:4). Whether the one that had read everything names him is left as it came: not in the last year (16:27), and twice after (21:3).
"""
_old = (H / "TOLD-LIFE-CONCORDANCE.md").read_text(encoding="utf-8"); _k = _old.find("## The earlier scenes traced"); conc += ("\n" + _old[_k:] if _k > 0 else "")
(H / "TOLD-LIFE-CONCORDANCE.md").write_text(conc, encoding="utf-8"); print(len(PLAN), "chapters", tv, "verses", tw, "words; rows", rn, "no place", re_, "untraced scene verses", sv)
