"""Check a writer's file against the vision: quoted phrases at the cited chapter:verse; runs of five words shared with the vision; reach.
    python3 writers/check_writer.py writers/WRITER-*.md"""
import re, sys, pathlib
H = pathlib.Path(__file__).resolve().parents[1]
V = (H / "THE-COMPLETION-OF-JACK-FEIST.md").read_text(encoding="utf-8")
ch = {}
for m in re.finditer(r"^## Chapter (\d+)\n(.*?)(?=^## Chapter |\n---\n)", V, re.M | re.S):
    for v in re.finditer(r"\*\*(\d+)\*\* (.*?)(?=\*\*\d+\*\* |\Z)", m.group(2), re.S): ch[(int(m.group(1)), int(v.group(1)))] = re.sub(r"\s+", " ", v.group(2)).strip()
tok = lambda s: re.findall(r"[a-z0-9']+", s.lower().replace("’", "'"))
vt = tok(re.sub(r"\*\*\d+\*\*", " ", V)); five = {tuple(vt[i:i + 5]) for i in range(len(vt) - 4)}
nq = lambda s: re.sub(r"\s+", " ", s.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')).strip().lower()
for f in sys.argv[1:]:
    t = pathlib.Path(f).read_text(encoding="utf-8"); cut = re.search(r"^\|.*\|\s*$", t, re.M)
    text = t[:cut.start()] if cut else t
    verses = re.findall(r"\*\*(\d+)\*\* (.*?)(?=\*\*\d+\*\* |\n\n|\Z)", text, re.S)
    gt = tok(re.sub(r"\*\*\d+\*\*", " ", " ".join(v for _, v in verses)))
    shared = sorted({" ".join(gt[i:i + 5]) for i in range(len(gt) - 4) if tuple(gt[i:i + 5]) in five})
    rows = [r for r in re.findall(r"^\|(.+)\|\s*$", t, re.M) if not re.match(r"\s*:?-{2,}", r.split("|")[0]) and not r.strip().lower().startswith("verse")]
    ok = bad = none = 0; misses = []
    for r in rows:
        c = [x.strip() for x in r.split("|")]
        if len(c) < 3: continue
        src = c[1]
        if src in ("—", "-", "–", ""): none += 1; continue
        hit = False
        for cv, q in re.findall(r"(\d+:\d+)[^“\"]*[“\"]([^”\"]+)[”\"]", src):
            a, b = map(int, cv.split(":")); hit = True
            if (a, b) in ch and nq(q).rstrip(".…") in nq(ch[(a, b)]): ok += 1
            else: bad += 1; misses.append((c[0], cv, q[:60]))
        if not hit: bad += 1; misses.append((c[0], "no chapter:verse with a quoted phrase", src[:60]))
    print(f"\n{pathlib.Path(f).name}: {len(gt)} words, {len(verses)} verses, {len(rows)} rows; quotes right {ok}, wrong {bad}, rows with no place {none}; five-word runs shared with the vision: {len(shared)}")
    for s in shared[:12]: print("   shared:", s)
    for m in misses[:12]: print("   miss:", m)
