"""Check the second sealed list by the rule of check.py; writes check2.json."""
import json, sys, random
sys.argv = [sys.argv[0]]
import check as C1
from rows2_sealed import ROWS
res = []
for (mt, sig, named, gp, hp, kind, what) in ROWS:
    g = C1.greek_holds(mt, gp); hf = C1.heb_find(sig, hp); he = C1.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})
s = {"sealed": f"{sum(r['holds'] for r in res)} of {len(res)} ({sum(r['holds_extant'] for r in res)} on extant letters)",
     "exact": f"{sum(r['holds'] for r in res if r['kind']=='E')} of {sum(1 for r in res if r['kind']=='E')}"}
rng = random.Random(1); sigs = [r["scroll"] for r in res]; acc = []
for _ in range(60):
    p = sigs[:]; rng.shuffle(p); n = ok = 0
    for r, x in zip(res, p):
        if x == r["scroll"]: continue
        n += 1; ok += bool(C1.heb_find(x, r["hebrew_patterns"]))
    acc.append(ok / n)
s["exchanged_scrolls_acceptance"] = round(sum(acc) / len(acc), 3)
json.dump({"summary": s, "rows": res}, open(C1.H / "check2.json", "w"), ensure_ascii=False, indent=1)
print(s)
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"])

CORR = {
 ("11:10-14; 17:10-12", "4Q558"): {"greek": ["ηλει|ηλια"], "why": "Nestle 1904 spells Ἠλείας"},
 ("27:52-53", "4Q385"): {"hebrew": ["עצמ", "יחיו|ויחיו"], "why": "the seat has ויחיו, they lived, not a verb of standing"},
 ("14:24-32", "1QHa"): {"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"])
    g = C1.greek_holds(r["matt"], gp); hf = C1.heb_find(r["scroll"], hp); he = C1.heb_find(r["scroll"], hp, extant=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})
s["after_corrections"] = f"{sum(r['holds'] for r in res) + sum(c['holds'] for c in corr)} of {len(res)}"
json.dump({"summary": s, "rows": res, "corrections": corr}, open(C1.H / "check2.json", "w"), ensure_ascii=False, indent=1)
print(corr); print(s)
