"""The arrow, second run: calibrated on transforms, by row, frozen before the disputed rows are read.

DESIGN, fixed before the run (2026-11-30), after the first run failed (ARROW.md; that seal, criterion and
failure stand as they were):

Calibration sets, each a retelling whose direction is not in dispute, Greek to Greek, both in the seats:
  K→C  Kingdoms (Swete, 1–4 Kgdms) retold in Paraleipomena (1–2 Chron). A row is a verse of Chronicles and the
       verse of Kingdoms sharing most content stems with it, kept if they share at least four and the overlap is at
       least a quarter of the smaller set (Jaccard ≥ 0.25 is too strict for paraphrase; the share of the smaller is used).
  K→J  Kingdoms retold in Josephus, Antiquities 6–10. A row is a section of Josephus and the three verses of
       Kingdoms around the verse sharing most content stems with it, kept if they share at least four.
Features (target minus source): the five of the first run, and a sixth:
  RES  local embeddedness of the shared words: for each shared stem, how often it recurs in the five verses (or
       sections) on either side of the row in each text, against what its frequency in that book predicts; RES is
       the mean, over shared stems, of log(observed+0.5 / expected+0.5) in the source less the same in the target.
       Positive when the shared words are more at home in the source's own neighbourhood than in the target's:
       the residue of a configuration that had its reasons where it came from.
Per row, a feature's value is its value on the true pair less its mean over twenty exchanged pairs (the same
source against other rows' targets from the same books), which removes what the two books differ in generally.
Task 1, direction recovery by row: the sign is fixed on K→C (the sign of the median row value) and frozen; a feature
passes if, under that sign, at least 60 per cent of rows are recovered in K→C and in K→J, with a one-sided binomial
p below 0.01 in each. Reversal is the same rows read backwards and is recovered at the complement by construction,
so the per-row rate is the test.
Task 2, reading: only passing features, with sign and rule frozen, are read on the Revelation ↔ Matthew rows: the share
of rows recovered as Revelation → Matthew, with its binomial p against one half. Between 40 and 60 per cent with p
above 0.05, the instrument abstains. The quotation sets of the first run (Septuagint → Matthew, Septuagint →
Revelation) are read the same way and reported, as a check of the conditioning: a quotation is not expected to pass.
Owed, not run here: common-source resistance (two derivatives of one antecedent), and the Secret Works II control.
"""
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 UM as _UM  # where the corpora are: see paths.py
import re, glob, math, random, collections, json, pathlib, sys
H = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(H))
import arrow as A
C = A.C

def load_swete(n):
    out = {}
    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 A.marked(raw): continue
            w = A.strip(raw); lk = A.lookup(w)
            toks.append((w, lk[0] if lk else None, lk[1] if lk else "", lk[2] if lk else "", raw[0].isupper()))
        out[(int(m[1]), int(m[2]))] = toks
    return out
KG = {}
for i, n in enumerate(("011", "012", "013", "014"), 1):
    for k, v in load_swete(n).items(): KG[(i,) + k] = v
CH = {}
for i, n in enumerate(("015", "016"), 1):
    for k, v in load_swete(n).items(): CH[(i,) + k] = v
AJ = {}
for l in open(C + "josephus/text/AJ.txt", encoding="utf-8"):
    r, t = l.rstrip("\n").split("\t", 1); m = re.match(r"AJ (\d+)\.(\d+)", r)
    if not m or not 6 <= int(m[1]) <= 10: continue
    toks = []
    for raw in re.findall(r"[Ͱ-Ͽἀ-῿]+", t):
        w = A.strip(raw); lk = A.lookup(w)
        toks.append((w, lk[0] if lk else None, lk[1] if lk else "", lk[2] if lk else "", raw[0].isupper()))
    AJ[(int(m[1]), int(m[2]))] = toks
def bookcount(d): return collections.Counter(A.stem(x[0]) for v in d.values() for x in v if A.content(x[0]))
A.BOOKCOUNT.update({"Kgdms": bookcount(KG), "Chron": bookcount(CH), "AJ": bookcount(AJ)})
UNITS = {"Kgdms": KG, "Chron": CH, "AJ": AJ}
ORDER = {b: sorted(d) for b, d in UNITS.items()}
ORDER["Matt"] = sorted(k for k in A.NTTOK if k[0] == "Matt"); ORDER["Rev"] = sorted(k for k in A.NTTOK if k[0] == "Rev")
UNITS["Matt"] = {k: A.NTTOK[k] for k in ORDER["Matt"]}; UNITS["Rev"] = {k: A.NTTOK[k] for k in ORDER["Rev"]}
IDX = {b: {k: i for i, k in enumerate(o)} for b, o in ORDER.items()}

def neigh(book, keys, w=5):
    """Stems of the units within w on either side of the row's units, the row's own units excluded."""
    ix = sorted(IDX[book][k] for k in keys if k in IDX[book])
    if not ix: return collections.Counter()
    lo, hi = ix[0] - w, ix[-1] + w; own = set(ix); c = collections.Counter()
    for i in range(max(0, lo), min(len(ORDER[book]), hi + 1)):
        if i in own: continue
        c.update(A.stem(x[0]) for x in UNITS[book][ORDER[book][i]] if A.content(x[0]))
    return c
def res(Sk, Tk, sb, tb, sh):
    if not sh: return None
    nS, nT = neigh(sb, Sk), neigh(tb, Tk); bs, bt = A.BOOKCOUNT[sb], A.BOOKCOUNT[tb]
    totS, totT = sum(bs.values()), sum(bt.values()); mS, mT = sum(nS.values()), sum(nT.values())
    v = []
    for w in sh:
        eS = mS * bs[w] / totS; eT = mT * bt[w] / totT
        v.append(math.log((nS[w] + 0.5) / (eS + 0.5)) - math.log((nT[w] + 0.5) / (eT + 0.5)))
    return sum(v) / len(v)

def tok(book, keys): return [x for k in keys for x in UNITS[book].get(k, [])]
def allfeats(Sk, Tk, sb, tb):
    S, T = tok(sb, Sk), tok(tb, Tk); f = A.feats(S, T, sb, tb)
    r = res(Sk, Tk, sb, tb, A.stems_of(S) & A.stems_of(T))
    if r is not None: f["RES"] = r
    return f

def build_kc():
    rows = []; inv = collections.defaultdict(set)
    for k, v in KG.items():
        for s in A.stems_of(v): inv[s].add(k)
    for k, v in CH.items():
        T = A.stems_of(v)
        if len(T) < 4: continue
        cnt = collections.Counter(kk for s in T for kk in inv[s])
        if not cnt: continue
        best, n = cnt.most_common(1)[0]; S = A.stems_of(KG[best])
        if n >= 4 and n / min(len(S), len(T)) >= 0.25: rows.append(([best], [k], "Kgdms", "Chron"))
    return rows
def build_kj():
    rows = []; inv = collections.defaultdict(set)
    for k, v in KG.items():
        for s in A.stems_of(v): inv[s].add(k)
    for k, v in AJ.items():
        T = A.stems_of(v); cnt = collections.Counter(kk for s in T for kk in inv[s])
        if not cnt: continue
        best, n = cnt.most_common(1)[0]
        if n < 4: continue
        i = IDX["Kgdms"][best]; Sk = ORDER["Kgdms"][max(0, i - 1):i + 2]
        rows.append((Sk, [k], "Kgdms", "AJ"))
    return rows
def ntkeys(book, spec):
    out = []
    for part in re.split(r"\s*;\s*", str(spec)):
        m = re.match(r"(\d+):(\d+)(?:-(\d+))?$", part.strip())
        if m: out += [(book, int(m[1]), v) for v in range(int(m[2]), int(m[3] or m[2]) + 1) if (book, int(m[1]), v) in UNITS[book]]
    return out

def per_row(rows, reps=20, seed=5):
    rng = random.Random(seed); out = []
    for i, (Sk, Tk, sb, tb) in enumerate(rows):
        f = allfeats(Sk, Tk, sb, tb); ex = collections.defaultdict(list)
        for _ in range(reps):
            j = rng.randrange(len(rows))
            if j == i: continue
            for kk, v in allfeats(Sk, rows[j][1], sb, rows[j][3]).items(): ex[kk].append(v)
        out.append({k: f[k] - sum(ex[k]) / len(ex[k]) for k in f if ex.get(k)})
    return out
def binom_p(k, n):            # one-sided P(X >= k), X ~ Bin(n, 1/2)
    return sum(math.comb(n, i) for i in range(k, n + 1)) / 2 ** n
def recovery(vals, sign):
    v = [x for x in vals if x != 0]; k = sum(1 for x in v if x * sign > 0)
    return {"rows": len(v), "recovered": k, "rate": round(k / len(v), 3) if v else None, "p": binom_p(k, len(v)) if v else None}

if __name__ == "__main__":
    KC, KJ = build_kc(), build_kj()
    L = json.load(open(str(_UM)+"/map/rev-matthew-ledger.json"))["rows"]
    RM = [(ntkeys("Rev", r["rev"]), ntkeys("Matt", r["matt"]), "Rev", "Matt") for r in L]
    RM = [r for r in RM if r[0] and r[1]]
    out = {"rows": {"K→C": len(KC), "K→J": len(KJ), "Rev↔Matt": len(RM)}}
    PR = {"K→C": per_row(KC), "K→J": per_row(KJ), "Rev→Matt": per_row(RM)}
    feats = sorted({k for r in PR["K→C"] for k in r})
    crit = {}
    for f in feats:
        kc = [r[f] for r in PR["K→C"] if f in r]; kj = [r[f] for r in PR["K→J"] if f in r]
        med = sorted(kc)[len(kc) // 2]; sign = 1 if med > 0 else -1
        a, b = recovery(kc, sign), recovery(kj, sign)
        ok = all(x["rate"] and x["rate"] >= 0.60 and x["p"] < 0.01 for x in (a, b))
        crit[f] = {"frozen_sign": sign, "K→C": a, "K→J": b, "passes": ok}
    out["calibration"] = crit
    reading = {}
    for f, c in crit.items():
        rm = recovery([r[f] for r in PR["Rev→Matt"] if f in r], c["frozen_sign"])
        if c["passes"]:
            rate, p, pr = rm["rate"], rm["p"], binom_p(rm["rows"] - rm["recovered"], rm["rows"])
            verdict = "Revelation → Matthew" if p < 0.05 else ("Matthew → Revelation" if pr < 0.05 else "abstains")
            reading[f] = dict(rm, p_reverse=pr, verdict=verdict)
        else:
            reading[f] = dict(rm, verdict="not read: feature failed calibration")
    out["reading_rev_matt"] = reading
    json.dump(out, open(H / "arrow2.json", "w"), ensure_ascii=False, indent=1)
    print(json.dumps(out, ensure_ascii=False, indent=1))
