"""The prophets recomposed in Revelation: a known arrow of the visionary kind.

DESIGN, fixed before the run (2026-11-30):
Rows P→R. For every verse of Revelation, the verse of the prophets (Swete: Isaiah, Jeremiah, Ezekiel, Daniel
(Theodotion), the Twelve) sharing most content stems with it; a row is kept if they share at least three and the
share is at least 0.3 of the smaller set. Revelation is later than the prophets on every account, so the arrow
is known; the operation is recomposition into vision, not quotation (Revelation names no prophet it uses).
Relation control: the same alignment run from 1 Maccabees (a Greek book of the Septuagint that is not a
recomposition of the prophets) gives the rate at which the rule makes rows by chance; reported per verse.
Direction: the six measures of arrow2.py, per row less the exchanged-pair mean, read with the signs frozen on
Kingdoms → Chronicles in the second run (arrow2.json), and reported as recovery rates with one-sided binomial p.
This asks whether the retelling signature (the source's verb becomes the target's noun) also marks recomposition
into vision. No criterion is applied to the disputed rows here and they are not read.
Order: for each prophet with at least eight rows, Spearman's rho between the place of the source verse in its book
and the place of the Revelation verse in Revelation, with a permutation p (2,000). The same statistic for the
retellings (K→C, K→J) and for the ledger (Revelation → Matthew), for comparison of operations. Order is reported as
a property of the operation, not as a sign of direction.
"""
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 json, math, random, collections, re, pathlib, sys
H = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(H))
import arrow as A, arrow2 as B
PROPH = {"Isa": "048", "Jer": "049", "Ezek": "053", "Dan": "057", "Hos": "036", "Joel": "039", "Amos": "037", "Obad": "040",
         "Jonah": "041", "Mic": "038", "Nah": "042", "Hab": "043", "Zeph": "044", "Hag": "045", "Zech": "046", "Mal": "047"}
for b, n in PROPH.items():
    d = {(b,) + k: v for k, v in B.load_swete(n).items()}
    B.UNITS[b] = d; B.ORDER[b] = sorted(d); B.IDX[b] = {k: i for i, k in enumerate(B.ORDER[b])}
    A.BOOKCOUNT[b] = collections.Counter(A.stem(x[0]) for v in d.values() for x in v if A.content(x[0]))
MAC = {(1,) + k: v for k, v in B.load_swete("023").items()}

inv = collections.defaultdict(set)
for b in PROPH:
    for k, v in B.UNITS[b].items():
        for s in A.stems_of(v): inv[s].add((b, k))
def align(units):
    rows = []
    for k, v in units.items():
        T = A.stems_of(v)
        if len(T) < 3: continue
        cnt = collections.Counter(x for s in T for x in inv[s])
        if not cnt: continue
        (b, kk), n = cnt.most_common(1)[0]; S = A.stems_of(B.UNITS[b][kk])
        if n >= 3 and n / min(len(S), len(T)) >= 0.3: rows.append(([kk], [k], b, "Rev"))
    return rows

def spearman(xs, ys):
    def rank(a):
        o = sorted(range(len(a)), key=lambda i: a[i]); r = [0] * len(a)
        for j, i in enumerate(o): r[i] = j
        return r
    rx, ry = rank(xs), rank(ys); n = len(xs); m = (n - 1) / 2
    num = sum((a - m) * (b - m) for a, b in zip(rx, ry)); den = sum((a - m) ** 2 for a in rx)
    return num / den if den else 0.0
def order_test(pairs, seed=3):
    xs = [p[0] for p in pairs]; ys = [p[1] for p in pairs]; rho = spearman(xs, ys); rng = random.Random(seed); ge = 0
    for _ in range(2000):
        y2 = ys[:]; rng.shuffle(y2); ge += spearman(xs, y2) >= rho
    return {"rows": len(pairs), "rho": round(rho, 3), "p": round((ge + 1) / 2001, 4)}

if __name__ == "__main__":
    PR_rows = align(B.UNITS["Rev"])
    mac_rows = align(MAC)
    out = {"rows": {"P→R": len(PR_rows), "Revelation verses": len(B.UNITS["Rev"]), "1 Maccabees rows (control)": len(mac_rows),
                    "1 Maccabees verses": len(MAC)},
           "rows_per_verse": {"Revelation": round(len(PR_rows) / len(B.UNITS["Rev"]), 3), "1 Maccabees": round(len(mac_rows) / len(MAC), 3)},
           "by_prophet": dict(collections.Counter(r[2] for r in PR_rows).most_common())}
    crit = json.load(open(H / "arrow2.json"))["calibration"]
    pr = B.per_row(PR_rows)
    out["direction_with_frozen_signs"] = {f: B.recovery([r[f] for r in pr if f in r], c["frozen_sign"]) for f, c in crit.items()}
    order = {}
    for b in PROPH:
        pairs = [(B.IDX[b][r[0][0]], B.IDX["Rev"][r[1][0]]) for r in PR_rows if r[2] == b]
        if len(pairs) >= 8: order[f"{b}→Rev"] = order_test(pairs)
    KC, KJ = B.build_kc(), B.build_kj()
    order["Kgdms→Chron"] = order_test([(B.IDX["Kgdms"][r[0][0]], B.IDX["Chron"][r[1][0]]) for r in KC])
    order["Kgdms→AJ"] = order_test([(B.IDX["Kgdms"][r[0][1] if len(r[0]) > 1 else r[0][0]], B.IDX["AJ"][r[1][0]]) for r in KJ])
    L = json.load(open(str(_UM)+"/map/rev-matthew-ledger.json"))["rows"]
    lp = []
    for r in L:
        rk, mk = B.ntkeys("Rev", r["rev"]), B.ntkeys("Matt", r["matt"])
        if rk and mk: lp.append((B.IDX["Rev"][rk[0]], B.IDX["Matt"][mk[0]]))
    order["Rev→Matt (ledger)"] = order_test(lp)
    out["order"] = order
    json.dump(out, open(H / "arrow3.json", "w"), ensure_ascii=False, indent=1)
    print(json.dumps(out, ensure_ascii=False, indent=1))
