"""Check the sealed rows against the seats, and run the exchanged-pairings control. Writes 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
from rows_sealed import ROWS
H = pathlib.Path(__file__).resolve().parent
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("׳", "")
    if extant: t = re.sub(r"\[[^\]]*\]", lambda m: " " + "·" * (len(m.group(0)) - 2) + " ", t)
    else: t = t.replace("[", "").replace("]", "")
    t = re.sub(r"[?#ε׃]", " ", t)
    return t.translate(FIN)

MT = {}
for l in open(C / "gnt-nestle1904/text/Matt.txt", encoding="utf-8"):
    r, t = l.rstrip("\n").split("\t", 1); MT[r.split(" ", 1)[1]] = gnorm(t)

SCROLL = collections.defaultdict(list)          # siglum -> [(locus, full, extant)]
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 mverses(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 MT]
    return out

def greek_holds(spec, pats):
    txt = " ".join(MT[v] for v in mverses(spec))
    return all(re.search(p, txt) for p in pats)

def heb_find(sig, pats, win=4, extant=False):
    lines = SCROLL.get(sig, []); k = 2 if extant else 1
    for i in range(len(lines)):
        block = " ".join(x[k] for x in lines[i:i + win])
        if all(re.search(p, block) for p in pats):
            return lines[i][0] + "–" + lines[min(i + win, len(lines)) - 1][0]
    return None

res = []
for (mt, sig, named, gp, hp, kind, what) in ROWS:
    g = greek_holds(mt, gp); hf = heb_find(sig, hp); he = heb_find(sig, hp, extant=True)
    res.append({"matt": mt, "scroll": sig, "named": named, "kind": kind, "what": what, "greek": g,
                "hebrew_at": hf, "hebrew_extant_at": he, "holds": bool(g and hf), "holds_extant": bool(g and he),
                "greek_patterns": gp, "hebrew_patterns": hp})

ex = [r for r in res if r["kind"] == "EX"]; sealed = [r for r in res if r["kind"] != "EX"]
summary = {"example": f"{sum(r['holds'] for r in ex)} of {len(ex)} ({sum(r['holds_extant'] for r in ex)} on extant letters only)",
           "sealed": f"{sum(r['holds'] for r in sealed)} of {len(sealed)} ({sum(r['holds_extant'] for r in sealed)} on extant letters only)",
           "named_exact": f"{sum(r['holds'] for r in sealed if r['kind']=='E')} of {sum(1 for r in sealed if r['kind']=='E')}"}

# control: each row's Hebrew patterns sought in another row's scroll (sigla exchanged), 60 times
rng = random.Random(0); acc = []
sigs = [r["scroll"] for r in res]
for _ in range(60):
    perm = sigs[:]; rng.shuffle(perm); n = ok = 0
    for r, s in zip(res, perm):
        if s == r["scroll"]: continue
        n += 1; ok += bool(heb_find(s, r["hebrew_patterns"]))
    acc.append(ok / n)
summary["exchanged_scrolls_acceptance"] = round(sum(acc) / len(acc), 3)
# second control: the Hebrew patterns sought in the whole non-biblical corpus outside the named scroll
outside = 0
for r in res:
    if any(heb_find(s, r["hebrew_patterns"]) for s in SCROLL if s != r["scroll"]): outside += 1
summary["rows_whose_hebrew_also_stands_elsewhere"] = f"{outside} of {len(res)}"
json.dump({"summary": summary, "rows": res}, open(H / "check.json", "w"), ensure_ascii=False, indent=1)
print(json.dumps(summary, ensure_ascii=False, indent=1))
for r in res:
    print(("HOLD " if r["holds"] else "fail ") + ("(ext) " if r["holds_extant"] else "      "), r["kind"], r["matt"], r["scroll"], r["named"], "| greek", r["greek"], "| at", r["hebrew_at"])

# ── corrections after the sealed run, each for the seat's spelling or the window; counted apart ──
CORR = {
 ("18:15-16", "CD"): {"hebrew": ["הוכח|הוכיח|תוכיח|תוכחת", "עדימ"], "why": "the seat spells בהוכח"},
 ("19:28", "11Q19"): {"hebrew": ["שנימ עשר", "נשי", "משפט"], "why": "the seat spells the princes נשיי"},
 ("22:39", "CD"): {"hebrew": ["לאהוב", "אחיהו", "כמו?הו"], "why": "the seat spells כמהו"},
 ("12:11", "CD"): {"greek": ["προβατ", "βοθυν", "σαββα"], "why": "Matthew has the dative plural σάββασιν"},
 ("11:5", "4Q521"): {"window": 5, "why": "the four members stand in lines 8 and 12, five lines"},
 ("16:18", "1QHa"): {"hebrew": ["סלע", "שערי", "סוד"], "why": "the seat has סוד, the foundation, not יסוד"},
 ("16:19; 18:18", "CD"): {"hebrew": ["קשר|קשרי", "חרצו?בות"], "why": "the seat spells חרצובות"},
}
corr = []
for r in res:
    c = CORR.get((r["matt"], r["scroll"]))
    if not c or r["holds"]: continue
    gp = c.get("greek", r["greek_patterns"]); hp = c.get("hebrew", r["hebrew_patterns"]); w = c.get("window", 4)
    g = greek_holds(r["matt"], gp); hf = heb_find(r["scroll"], hp, w); he = heb_find(r["scroll"], hp, w, True)
    corr.append({"matt": r["matt"], "scroll": r["scroll"], "why": c["why"], "holds": bool(g and hf), "holds_extant": bool(g and he), "at": hf})
summary["after_corrections"] = f"{sum(r['holds'] for r in sealed) + sum(c['holds'] for c in corr)} of {len(sealed)}"
json.dump({"summary": summary, "rows": res, "corrections": corr}, open(H / "check.json", "w"), ensure_ascii=False, indent=1)
print(json.dumps(corr, ensure_ascii=False, indent=1)); print(summary["after_corrections"])
