"""The arrow, calibrated on the Septuagint.

DESIGN, fixed before the run (2026-11-30):

Known-direction pairs. (a) Septuagint → Matthew: the 85 rows of the notebook's scripture list (x1.py: 42 explicit
quotations, 43 tacit). (b) Septuagint → Revelation: the 88 rows of rev_lxx_sealed.py. In each row the Septuagint
place is the verse, within two verses of the one named (or the same verse a chapter either side), that shares
most stems with the New Testament span.
The rows under test. (c) Revelation ↔ Matthew: the 158 rows of the ledger, read both ways.

Features of a row, each computed as target minus source, so each reverses sign when the row is read backwards:
  NAT    nativeness: over the stems the two spans share, the mean log of (relative frequency in the source book
         / relative frequency in the target book), less the same mean over the stems they do not share. Positive
         when the shared words are more at home in the source than the two books' vocabularies are in general.
  NV     at shared stems with a part of speech known on both sides: (noun or adjective in the source, verb in the
         target) minus (verb in the source, noun or adjective in the target), over the shared stems counted.
  PAST   at shared verb stems: (target a past indicative, source a future, present, imperative or subjunctive)
         minus the reverse, over the shared verbs counted.
  NAMES  proper names in the target span not in the source span, minus the reverse, per hundred words.
  EXP    log of the target span's length over the source span's.
Parts of speech, tense and mood come from MACULA Greek (Nestle 1904) for the New Testament; for the Septuagint,
from the same tagging by word form, form by form, where the form occurs in the New Testament (coverage reported).
Swete's lines carry apparatus; only words bearing an accent or breathing are kept, which drops the apparatus.

The control within each set: exchanged pairs (each row's source with another row's target, twenty times). A
feature's pair-specific value is its mean on true rows less its mean on exchanged rows; its interval is a
bootstrap over rows (2,000 draws, 95 per cent).

The criterion: a feature carries the arrow if its pair-specific value has the same sign in (a) and in (b), and
the interval excludes zero in both. Only features that pass are read on (c): there, with Revelation as source and
Matthew as target, a pair-specific value of the calibrated sign is the signature of Revelation → Matthew, and of
the opposite sign the signature of Matthew → Revelation. Features that fail are reported and not read.
"""
import pathlib as _pl, sys as _sy; _sy.path.insert(0, str(next(p for p in _pl.Path(globals().get("__file__") or _pl.Path.cwd() / "_").resolve().parents if (p / "paths.py").exists()))); from paths import CORPORA as _CORP, UM as _UM  # where the corpora are: see paths.py
import json, re, glob, math, random, collections, unicodedata as U, pathlib, sys
H = pathlib.Path(__file__).resolve().parent
C = _CORP+"/"
MAC = "/tmp/fetch/macula/macula-greek/Nestle1904/tsv/macula-greek-Nestle1904.tsv"
def strip(t):
    t = U.normalize("NFD", t); return "".join(c for c in t if not U.combining(c)).lower().replace("ς", "σ")
def marked(t): return any(U.combining(c) for c in U.normalize("NFD", t))
STOP = set("αυτοσ αυτου αυτον αυτω αυτοισ αυτων αυτη αυτησ αυτην ουτοσ τουτο ταυτα τουτου εστιν εισιν εσται λεγει λεγων ειπεν παντα παντεσ "
           "υμων υμιν υμασ ημων ημιν ημασ οταν οπου ουδε μηδε αλλα εκεινοσ εκεινη εκεινου".split())
def stem(w): return w[:5]
def content(w): return len(w) >= 5 and w not in STOP

# ── MACULA: New Testament tokens with class, tense, mood; and a form dictionary for the Septuagint ──
NTTOK = collections.defaultdict(list)          # (book, c, v) -> [(form, cls, tense, mood, proper)]
FORM = collections.defaultdict(collections.Counter)
BOOKS = {"MAT": "Matt", "REV": "Rev"}
for line in open(MAC, encoding="utf-8"):
    f = line.rstrip("\n").split("\t")
    if f[0] == "xml:id" or len(f) < 14: continue
    ref, cls, typ, text, morph = f[1], f[3], f[4], f[8], f[13]
    m = re.match(r"(\w+) (\d+):(\d+)!", ref)
    if not m: continue
    w = strip(text); tense = mood = ""
    mm = re.match(r"V-(\d?)([PIFARL])[AMPDONE]?([ISOMNP])", morph)
    if mm: tense, mood = mm.group(2), mm.group(3)
    k = "verb" if cls == "verb" else ("noun" if cls in ("noun", "adj") else cls)
    FORM[w][(k, tense, mood)] += 1
    if m.group(1) in BOOKS: NTTOK[(BOOKS[m.group(1)], int(m.group(2)), int(m.group(3)))].append((w, k, tense, mood, typ == "proper"))
def lookup(w):
    c = FORM.get(w); return c.most_common(1)[0][0] if c else None

# ── the Septuagint, cleaned of apparatus ──
SW = {"Gen": "001", "Exod": "002", "Lev": "003", "Num": "004", "Deut": "005", "3Kgdms": "013", "4Kgdms": "014", "Ps": "027", "Prov": "029",
      "Sir": "034", "Hos": "036", "Amos": "037", "Mic": "038", "Joel": "039", "Jonah": "041", "Zech": "046", "Mal": "047", "Isa": "048",
      "Jer": "049", "Ezek": "053", "Dan": "057"}
LXX = {}; BOOKCOUNT = {}
for b, n in SW.items():
    LXX[b] = {}; cnt = collections.Counter()
    for l in open(glob.glob(C + f"lxx-swete/text/tlg{n}-*.txt")[0], encoding="utf-8"):
        if "\t" not in l: continue
        r, t = l.rstrip("\n").split("\t", 1); m = re.search(r"(\d+):(\d+)$", r)
        if not m: continue
        toks = []
        for raw in re.findall(r"[Ͱ-Ͽἀ-῿]+", t):
            if not marked(raw): continue
            w = strip(raw); lk = lookup(w)
            toks.append((w, lk[0] if lk else None, lk[1] if lk else "", lk[2] if lk else "", raw[0].isupper()))
        LXX[b][(int(m[1]), int(m[2]))] = toks
        cnt.update(stem(x[0]) for x in toks if content(x[0]))
    BOOKCOUNT[b] = cnt
for bk in ("Matt", "Rev"):
    BOOKCOUNT[bk] = collections.Counter(stem(x[0]) for k, v in NTTOK.items() if k[0] == bk for x in v if content(x[0]))

def ntspan(book, spec):
    out = []
    for part in re.split(r"\s*;\s*", str(spec)):
        m = re.match(r"(\d+):(\d+)(?:-(\d+))?$", part.strip())
        if m:
            for v in range(int(m[2]), int(m[3] or m[2]) + 1): out += NTTOK.get((book, int(m[1]), v), [])
    return out
def stems_of(toks): return {stem(x[0]) for x in toks if content(x[0])}
def lxxspan(b, c, v, target):
    T = stems_of(target); best = (-1, [])
    cands = [(c, v + d) for d in range(-2, 3)] + [(c - 1, v), (c + 1, v)]
    for k in cands:
        toks = LXX[b].get(k)
        if toks is None: continue
        o = len(stems_of(toks) & T)
        if o > best[0]: best = (o, toks)
    return best[1]

# ── features ──
def feats(S, T, sb, tb):
    sS, sT = stems_of(S), stems_of(T); sh = sS & sT; un = (sS | sT) - sh
    out = {}
    cs, ct = BOOKCOUNT[sb], BOOKCOUNT[tb]; ns, nt = sum(cs.values()), sum(ct.values())
    def lr(w): return math.log((cs[w] + 0.5) / ns) - math.log((ct[w] + 0.5) / nt)
    if sh and un: out["NAT"] = sum(map(lr, sh)) / len(sh) - sum(map(lr, un)) / len(un)
    posS = {}; posT = {}
    for x in S:
        if content(x[0]) and x[1]: posS.setdefault(stem(x[0]), x)
    for x in T:
        if content(x[0]) and x[1]: posT.setdefault(stem(x[0]), x)
    both = [w for w in sh if w in posS and w in posT]
    if both:
        nv = sum((posS[w][1] == "noun" and posT[w][1] == "verb") - (posS[w][1] == "verb" and posT[w][1] == "noun") for w in both)
        out["NV"] = nv / len(both)
        vb = [w for w in both if posS[w][1] == "verb" and posT[w][1] == "verb"]
        past = lambda x: x[3] == "I" and x[2] in "AIL"
        nonpast = lambda x: x[2] == "F" or x[3] in "MS" or (x[3] == "I" and x[2] == "P")
        if vb: out["PAST"] = sum((past(posT[w]) and nonpast(posS[w])) - (past(posS[w]) and nonpast(posT[w])) for w in vb) / len(vb)
    names = lambda X: {x[0] for x in X if x[4]}
    lenS, lenT = max(1, len(S)), max(1, len(T))
    out["NAMES"] = 100 * (len(names(T) - names(S)) / lenT - len(names(S) - names(T)) / lenS)
    out["EXP"] = math.log(lenT / lenS)
    return out

def build(rows):
    """rows: [(S tokens, T tokens, source book, target book)] -> per-feature lists of true values and exchanged values."""
    tru = collections.defaultdict(list); exc = collections.defaultdict(list); rng = random.Random(7)
    per_row = []
    for i, (S, T, sb, tb) in enumerate(rows):
        f = feats(S, T, sb, tb); per_row.append(f)
        for k, v in f.items(): tru[k].append((i, v))
        for _ in range(20):
            j = rng.randrange(len(rows))
            if j == i: continue
            g = feats(S, rows[j][1], sb, rows[j][3])
            for k, v in g.items(): exc[k].append((i, v))
    return tru, exc, per_row

def summarize(tru, exc, n):
    out = {}; rng = random.Random(11)
    for k in sorted(set(tru) | set(exc)):
        tv = collections.defaultdict(list); ev = collections.defaultdict(list)
        for i, v in tru.get(k, []): tv[i].append(v)
        for i, v in exc.get(k, []): ev[i].append(v)
        idx = sorted(set(tv) | set(ev))
        def stat(sample):
            t = [v for i in sample for v in tv.get(i, [])]; e = [v for i in sample for v in ev.get(i, [])]
            if not t or not e: return None
            return sum(t) / len(t) - sum(e) / len(e)
        point = stat(idx); boots = sorted(x for x in (stat([rng.choice(idx) for _ in idx]) for _ in range(2000)) if x is not None)
        lo, hi = boots[int(0.025 * len(boots))], boots[int(0.975 * len(boots)) - 1]
        out[k] = {"pair_specific": round(point, 4), "ci95": [round(lo, 4), round(hi, 4)], "rows": len(tv),
                  "true_mean": round(sum(v for i, v in tru.get(k, [])) / max(1, len(tru.get(k, []))), 4)}
    return out

if __name__ == "__main__":
    sys.path.insert(0, str(_UM)+"/scripture")
    src = open(str(_UM)+"/scripture/x1.py", encoding="utf-8").read()
    EXPL = eval(re.search(r"EXPL=(\[.*?\])\n", src, re.S).group(1)); TAC = eval(re.search(r"TAC=(\[.*?\])\n", src, re.S).group(1))
    A = []
    for r in EXPL + TAC:
        m, b, c, v = r[:4]; T = ntspan("Matt", m); S = lxxspan(b, c, v, T)
        if S and T: A.append((S, T, b, "Matt"))
    from rev_lxx_sealed import ROWS as RR
    Bc = []
    for (rv, b, c, v, _) in RR:
        T = ntspan("Rev", rv); S = lxxspan(b, c, v, T)
        if S and T: Bc.append((S, T, b, "Rev"))
    L = json.load(open(str(_UM)+"/map/rev-matthew-ledger.json"))["rows"]
    Cc = []
    for r in L:
        S = ntspan("Rev", r.get("rev")); T = ntspan("Matt", r.get("matt"))
        if S and T: Cc.append((S, T, "Rev", "Matt"))
    cov = [x for rows in (A, Bc) for S, T, _, _ in rows for x in S if content(x[0])]
    res = {"rows": {"lxx_to_matthew": len(A), "lxx_to_revelation": len(Bc), "revelation_matthew": len(Cc)},
           "septuagint_pos_coverage": round(sum(1 for x in cov if x[1]) / len(cov), 3)}
    for name, rows in (("lxx_to_matthew", A), ("lxx_to_revelation", Bc), ("revelation_to_matthew", Cc)):
        tru, exc, _ = build(rows); res[name] = summarize(tru, exc, len(rows))
    passed = {}
    for k in res["lxx_to_matthew"]:
        a, b = res["lxx_to_matthew"][k], res["lxx_to_revelation"].get(k)
        if not b: continue
        sa, sb = a["pair_specific"], b["pair_specific"]
        ok = sa * sb > 0 and (a["ci95"][0] > 0 or a["ci95"][1] < 0) and (b["ci95"][0] > 0 or b["ci95"][1] < 0)
        passed[k] = {"passes": ok, "calibrated_sign": (1 if sa > 0 else -1) if ok else None}
    res["criterion"] = passed
    verdict = {}
    for k, p in passed.items():
        if not p["passes"]: continue
        c = res["revelation_to_matthew"][k]; s = c["pair_specific"]; ci = c["ci95"]
        sig = ci[0] > 0 or ci[1] < 0
        verdict[k] = ("Revelation → Matthew" if s * p["calibrated_sign"] > 0 else "Matthew → Revelation") + ("" if sig else " (interval includes zero)")
    res["reading_on_revelation_matthew"] = verdict
    json.dump(res, open(H / "arrow.json", "w"), ensure_ascii=False, indent=1)
    print(json.dumps(res, ensure_ascii=False, indent=1))
