"""Checks rev_rows_sealed.py (hash checked) against the seats, runs the exchanged-scroll control, and tests P1-P5. Writes rev_check.json."""
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  # where the corpora are: see paths.py
import json, re, random, unicodedata as U, pathlib, collections, hashlib, sys
H = pathlib.Path(__file__).resolve().parent; sys.path.insert(0, str(H))
assert hashlib.sha256((H / "rev_rows_sealed.py").read_bytes()).hexdigest() in (H / "rev_rows_sealed.seal.txt").read_text()
from rev_rows_sealed import ROWS, CITY, RULE
C = pathlib.Path(_CORP+"/")
def gnorm(t):
    t = U.normalize("NFD", t); return "".join(c for c in t if not U.combining(c)).lower().replace("ς", "σ")
FIN = str.maketrans("ךםןףץ", "כמנפצ")
def hnorm(t, extant):
    t = t.replace("׳", "")
    t = re.sub(r"\[[^\]]*\]", lambda m: " " + "·" * (len(m.group(0)) - 2) + " ", t) if extant else t.replace("[", "").replace("]", "")
    return re.sub(r"[?#ε׃]", " ", t).translate(FIN)
RV = {}
for l in open(C / "gnt-nestle1904/text/Rev.txt", encoding="utf-8"):
    r, t = l.rstrip("\n").split("\t", 1); RV[r.split(" ", 1)[1]] = gnorm(t)
SCROLL = collections.defaultdict(list)
for l in open(C / "dss/text/nonbiblical.txt", encoding="utf-8"):
    r, t = l.rstrip("\n").split("\t", 1); s, loc = r.split(" ", 1); SCROLL[s].append((loc, hnorm(t, False), hnorm(t, True)))
def verses(spec):
    out = []
    for part in re.split(r";\s*", spec):
        m = re.match(r"(\d+):(\d+)(?:-(\d+))?", part.strip()); c, a, z = int(m[1]), int(m[2]), int(m[3] or m[2])
        out += [f"{c}:{v}" for v in range(a, z + 1) if f"{c}:{v}" in RV]
    return out
def greek(spec, pats):
    txt = " ".join(RV[v] for v in verses(spec)); return all(re.search(p, txt) for p in pats)
def heb(sig, pats, win=4, extant=False):
    L = SCROLL.get(sig, []); k = 2 if extant else 1
    for i in range(len(L)):
        b = " ".join(x[k] for x in L[i:i + win])
        if all(re.search(p, b) for p in pats): return (i, L[i][0] + "–" + L[min(i + win, len(L)) - 1][0])
    return None
res = []
for (rv, sig, named, gp, hp, kind, what) in ROWS:
    g = greek(rv, gp); hf = heb(sig, hp); he = heb(sig, hp, extant=True)
    res.append({"rev": rv, "scroll": sig, "named": named, "kind": kind, "what": what, "greek": g, "hebrew_at": hf and hf[1],
                "line_index": hf and hf[0], "hebrew_extant_at": he and he[1], "holds": bool(g and hf), "holds_extant": bool(g and he)})
sealed = [r for r in res if r["kind"] != "EX"]
rng = random.Random(0); acc = []; sigs = [r["scroll"] for r in res]
for _ in range(60):
    for (rv, sig, named, gp, hp, kind, what) in ROWS:
        other = rng.choice([s for s in sigs if s != sig]); acc.append(bool(heb(other, hp)))
def col(loc):
    m = re.match(r"(\d+)", loc or ""); return int(m[1]) if m else None
def zone(sig, loc):
    if sig == "11Q19":
        c = col(loc); return "CITY" if c and c <= 47 else "RULE"
    return "CITY" if sig in CITY else "RULE" if sig in RULE else "OTHER"
held_rev = [r for r in res if r["holds"]]
mt = []
for f in ("../check.json", "../check2.json"):
    c = json.load(open(H / f)); ok = {(r["matt"], r["scroll"]) for r in c["rows"] if r["holds"]} | {(x["matt"], x["scroll"]) for x in c.get("corrections", []) if x["holds"]}
    mt += [r for r in c["rows"] if (r["matt"], r["scroll"]) in ok and r.get("kind") != "EX"]
zr = collections.Counter(zone(r["scroll"], r["hebrew_at"]) for r in held_rev); zm = collections.Counter(zone(r["scroll"], r.get("hebrew_at")) for r in mt)
both = sorted({r["scroll"] for r in held_rev} & {r["scroll"] for r in mt})
def idx(sig, loc):
    L = SCROLL.get(sig, []); first = (loc or "").split("–")[0]
    return next((i for i, x in enumerate(L) if x[0] == first), None)
near = 0; near_rows = []
for r in mt:
    i = idx(r["scroll"], r.get("hebrew_at"))
    for q in held_rev:
        if q["scroll"] == r["scroll"] and i is not None and q["line_index"] is not None and abs(i - q["line_index"]) <= 20:
            near += 1; near_rows.append((r["matt"], r["scroll"], r.get("hebrew_at"), q["rev"])); break
out = {"rows": res,
       "summary": {"sealed_held": f"{sum(r['holds'] for r in sealed)} of {len(sealed)} ({sum(r['holds_extant'] for r in sealed)} on extant letters)",
                   "examples_held": f"{sum(r['holds'] for r in res if r['kind']=='EX')} of 2",
                   "exact_held": f"{sum(r['holds'] for r in sealed if r['kind']=='E')} of {sum(1 for r in sealed if r['kind']=='E')}",
                   "exchanged_acceptance": round(sum(acc) / len(acc), 3)},
       "zones": {"revelation_held": dict(zr), "matthew_held": dict(zm)}, "scrolls_both": both,
       "matthew_rows_at_a_revelation_place": {"n": near, "of": len(mt), "rows": near_rows}}
nsh = sum(r['holds'] for r in sealed); nr = sum(zr.values()); nm = sum(zm.values())
out["P1"] = nsh >= 14
out["P2"] = (zr["CITY"] / nr >= 0.6) and (zm["RULE"] / nm >= 0.6)
out["P3"] = len(both) <= 4 and "1QSa" in both and "1QHa" in both
out["P4"] = near / len(mt) < 0.2
out["P5"] = out["summary"]["exchanged_acceptance"] < 0.15
json.dump(out, open(H / "rev_check.json", "w"), ensure_ascii=False, indent=1)
for r in res: print(("HOLD " if r["holds"] else "fail ") + ("x " if r["holds_extant"] else "  "), r["kind"], r["rev"], r["scroll"], r["hebrew_at"], "| greek", r["greek"])
print(json.dumps({k: v for k, v in out.items() if k != "rows"}, ensure_ascii=False, indent=1))
