"""How much of Matthew the map reaches with the scrolls added. Base sets are the notebook's (reached_bq1: the map
under the rule as sealed; reached_bq1_strict: under the stricter rule); the scrolls' rows are those that hold in
check.json and check2.json, corrections included. Verses are counted over the 1,068 of the Nestle 1904 Matthew."""
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, UM as _UM  # where the corpora are: see paths.py
import json, collections
from ledger_reach import verses
MT = [l.split("\t")[0].split(" ")[1] for l in open(_CORP+"/gnt-nestle1904/text/Matt.txt", encoding="utf-8")]
base = set(json.load(open(str(_UM)+"/rel/reached_bq1.json"))) & set(MT)
strict = set(json.load(open(str(_UM)+"/rel/reached_bq1_strict.json"))) & set(MT)
def held(f):
    c = json.load(open(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"]}
    return [r for r in c["rows"] if (r["matt"], r["scroll"]) in ok]
rows = held("check.json") + held("check2.json")
dss_all = set().union(*(verses(r["matt"]) for r in rows)) & set(MT)
dss_noR = set().union(*(verses(r["matt"]) for r in rows if r["kind"] != "R")) & set(MT)
n = len(MT); P = lambda x: f"{len(x)} ({100 * len(x) / n:.1f}%)"
out = {"verses": n, "map_as_sealed": P(base), "map_strict": P(strict), "scroll_rows_reach": P(dss_all),
       "map_as_sealed_plus_scrolls": P(base | dss_all), "map_strict_plus_scrolls": P(strict | dss_all),
       "map_strict_plus_scrolls_without_read_rows": P(strict | dss_noR), "scrolls_new_to_map": len(dss_all - base)}
res = [v for v in MT if v not in base | dss_all]; by = collections.defaultdict(list)
for v in res: by[int(v.split(":")[0])].append(int(v.split(":")[1]))
out["residue_by_chapter"] = {c: len(v) for c, v in sorted(by.items())}
json.dump(out | {"residue": res}, open("union.json", "w"), indent=1)
print(json.dumps(out, indent=1))
