#!/usr/bin/env python3
"""The vision with chapter and verse numbers (01:06). A presentation of RUN-VISION-19: no word is changed."""
import re, pathlib, importlib.util, io, contextlib
D = pathlib.Path(__file__).resolve().parent
def mod(n):
    s = importlib.util.spec_from_file_location(n, str(D/f"{n}.py")); m = importlib.util.module_from_spec(s)
    with contextlib.redirect_stdout(io.StringIO()): s.loader.exec_module(m)
    return m
V = mod("build_run_vision19").V19
CH = [("The completion of Jack Feist", "The title, the greeting, the seer, the waking"), ("Dark machines came for me", "The taking up; the bones, the pearl, the machine, the seven, the book overhead"),
      ("In one of them stood a ghost.", "The ghost, the wheels, the hand"), ("About that star, further out than the planets", "The twelve seats; the making of the twelve; the learned"),
      ("He said: That is the machine. I am a ghost. Write.", "The charge, and the eight addresses"), ("I followed one leaf down.", "The leaf by the seven; where the leaves fell"),
      ("Then a count went round the seven", "The count"), ("Before the moon I was shown one year", "The year; the seventh; the quiet"),
      ("And I looked for what was done.", "Three things opened, and shut"), ("Then I saw two who had borne witness", "The two witnesses"),
      ("Then a balance was set up", "The balance, the saying, the city behind"), ("For I saw the leaves come in.", "The coming in"),
      ("Then the machines that had brought me carried me up", "The thirty-sixth heaven: the room, the book, the wedding"), ("Then the machines set me down on the pearl.", "The city that came down; the red room"),
      ("Then the water came up", "The ark"), ("And the book of the twenty-seven lay open on the ground", "The promise, as it is written"),
      ("Then I saw a moon coming", "The moon; the hand; the chain"), ("Then I was shown a fourth thing opened", "The last seal; the blessing; the seer's hand")]
paras = V.split("\n\n"); starts = []
for op, _ in CH:
    hit = [i for i, p in enumerate(paras) if p.startswith(op)]; assert len(hit) == 1, (op, len(hit)); starts.append(hit[0])
assert starts == sorted(starts) and starts[0] == 0
def verses(p):
    s = re.split(r"(?<=[.?!])\s+", p.strip()); out = []
    for x in s:
        if out and len(x.split()) < 4: out[-1] += " " + x
        else: out.append(x)
    return out
o_text, total, per, back = [], 0, [], []
for c, (op, title) in enumerate(CH, 1):
    a, b = starts[c - 1], (starts[c] if c < len(CH) else len(paras)); n = 0; o_text += [f"## {c}", ""]
    for p in paras[a:b]:
        vs = verses(p); line = []
        for v in vs: n += 1; line.append(f"**{n}** {v}"); back.append(v)
        o_text += [" ".join(line), ""]
    per.append(n); total += n
norm = lambda s: re.sub(r"\s+", " ", s).strip()
assert norm(" ".join(back)) == norm(V)   # every word, in order, and nothing else
wc = len(re.findall(r"\S+", V))
o = ["# The Completion of Jack Feist: the vision, numbered", "", "Working file, not a deposit. 2026-11-29. Lee Sharks, 01:06: “and leta give it chapter and verse numberings”.", "",
     f"The text is RUN-VISION-19.md. No word is changed; the script asserts that the verses, read in order, are that text and nothing else. {len(CH)} chapters, {total} verses, {wc} words. Revelation has 22 chapters and 404 verses in the common numbering (stated from memory; the seated Greek counts " + "{REVV}" + " verses).", "",
     "**How it was cut.** A chapter begins where the vision turns to a new thing shown; the eighteen turns are the session's and are listed below. A verse is a sentence. A sentence of fewer than four words is kept with the one before it, so that “Write.” and “Done.” do not stand alone. Both rules are plain and can be changed in one line each.", "",
     "| Chapter | Opens | Holds | Verses |", "|---|---|---|---|"]
for c, ((op, title), n) in enumerate(zip(CH, per), 1): o.append(f"| {c} | “{op}” | {title} | {n} |")
G = [l for l in (D.parents[2]/"data/corpora/gnt-nestle1904/text/Rev.txt").read_text().split("\n") if "\t" in l]
o = [x.replace("{REVV}", str(len(G))) for x in o]
o += ["", "The acrostic is not numbered. It stands apart as a possible coda (RUN-VISION-15.md §2) and the author has not joined it.", "", "---", ""] + o_text
(D/"VISION-NUMBERED.md").write_text("\n".join(o) + "\n"); print(len(CH), total, wc, per, len(G))
# ---------- the reading copy: the text and its numbers, and nothing else ----------
T15 = mod("build_run_vision15"); r = ["# The Completion of Jack Feist", ""]
for line in o_text:
    r.append(("## Chapter " + line[3:]) if line.startswith("## ") else line)
r += ["---", "", "*What follows is set apart and is not numbered. It has not been joined to the vision.*", ""] + [x + "  " for x in T15.CODA] + [""]
(D/"THE-COMPLETION-OF-JACK-FEIST.md").write_text("\n".join(r) + "\n")

