"""Runs OCCAM.sealed.md (hash checked). Writes occam.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, hashlib, re, collections, pathlib, sys
H = pathlib.Path(__file__).resolve().parent
assert hashlib.sha256((H / "OCCAM.sealed.md").read_bytes()).hexdigest() in (H / "OCCAM.seal.txt").read_text()
src = (H.parent / "rev3/rev3.py").read_text(encoding="utf-8"); src = src[:src.index("rows=json.load(")]
ns = {}; exec(src, ns); cls = {f"{k[0]}:{k[1]}" if isinstance(k, tuple) else str(k): v for k, v in ns["cls"].items()}
from codes import F
inv = {r["id"]: r for r in json.load(open(H / "rows.inventory.json"))}
MT = [l.split("\t")[0].split(" ")[1] for l in open(_CORP+"/gnt-nestle1904/text/Matt.txt", encoding="utf-8")]
def verses(s):
    out = set()
    for part in re.split(r"[;,]\s*", s):
        m = re.match(r"\s*(\d+):(\d+)(?:[-–](\d+))?", part)
        if m: out |= {f"{m.group(1)}:{v}" for v in range(int(m.group(2)), int(m.group(3) or m.group(2)) + 1)}
    return out & set(MT)
reach = collections.defaultdict(set)
for i in F: reach[inv[i]["source"]] |= verses(inv[i]["matt"])
A = set().union(*(reach[s] for s in ("Septuagint, named", "Septuagint, tacit", "letters", "Josephus", "scrolls")))
REVS = reach["Revelation"] | reach["Philo, with Revelation"]; B = A | REVS
tot = collections.Counter(cls.get(v, "?") for v in MT)
def by(S): return {c: round(100 * sum(1 for v in S if cls.get(v) == c) / tot[c], 1) for c in ("MARK", "DOUBLE", "OWN")}
uniq = REVS - A
out = {"verses": len(MT), "classes": dict(tot), "A": len(A), "B": len(B), "A_pct": round(100 * len(A) / len(MT), 1), "B_pct": round(100 * len(B) / len(MT), 1),
       "revelation_unique": len(uniq), "A_by_class": by(A), "B_by_class": by(B), "unique_by_class": dict(collections.Counter(cls.get(v) for v in uniq)),
       "added_within_double_and_own": sum(1 for v in uniq if cls.get(v) in ("DOUBLE", "OWN")),
       "residue_B_by_class": {c: sum(1 for v in MT if v not in B and cls.get(v) == c) for c in ("MARK", "DOUBLE", "OWN")}}
out["P1"] = out["revelation_unique"] >= 150
out["P2"] = (out["B_by_class"]["DOUBLE"] - out["A_by_class"]["DOUBLE"] >= 10) and (out["B_by_class"]["OWN"] - out["A_by_class"]["OWN"] >= 10)
out["P3"] = out["B_pct"] > 50
json.dump(out, open(H / "occam.json", "w"), indent=1); print(json.dumps(out, indent=1))
