"""The notebook's Philo pair rule (two stems rare in the New Testament, 60 verses or fewer, standing together in one
section of Philo and in no verse of the Septuagint together), applied to Matthew's verses and to controls of the
same size: Epictetus in verse-sized pieces, and Mark and Luke. If the rule accepts Epictetus as often as Matthew,
its rows are not evidence of Philo as a source. Writes philo_control.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 re, json, glob, collections, itertools, unicodedata as U, pathlib
H = pathlib.Path(__file__).resolve().parent
C = _CORP+"/"
def stems(t):
    t = U.normalize("NFD", t); t = "".join(c for c in t if not U.combining(c)).lower().replace("ς", "σ")
    return {w[:5] for w in re.findall(r"[α-ω]+", t) if len(w) >= 5}
def units(files):
    out = []
    for f in files:
        for l in open(f, encoding="utf-8"):
            if "\t" in l: out.append(stems(l.split("\t", 1)[1]))
    return out
NT = {}
for f in sorted(glob.glob(C + "gnt-nestle1904/text/*.txt")):
    for l in open(f, encoding="utf-8"):
        r, t = l.rstrip("\n").split("\t", 1); NT[r] = stems(t)
freq = collections.Counter(s for ss in NT.values() for s in ss)
rare = {s for s, c in freq.items() if c <= 60}
def index(us):
    ix = collections.defaultdict(set)
    for i, ss in enumerate(us):
        for s in ss: ix[s].add(i)
    return ix
iP = index(units(sorted(glob.glob(C + "philo/text/*.txt")))); iL = index(units(sorted(glob.glob(C + "lxx-swete/text/*.txt"))))
def accepts(ss):
    r = sorted(ss & rare)
    for a, b in itertools.combinations(r, 2):
        if iL[a] & iL[b]: continue
        if iP[a] & iP[b]: return True
    return False
def nt(book): return [(r.split(" ", 1)[1], ss) for r, ss in NT.items() if r.startswith(book + " ")]
words = " ".join(l.strip() for l in open(C + "epictetus-dissertationes-schenkl-1916/text/dissertationes.txt", encoding="utf-8") if not l.startswith("[")).split()
EPI = [(f"w{i}", stems(" ".join(words[i:i + 19]))) for i in range(0, len(words), 19)]   # 19 words: Matthew's mean verse
out = {}
for name, vs in (("Matthew", nt("Matt")), ("Mark", nt("Mark")), ("Luke", nt("Luke")), ("Epictetus", EPI)):
    acc = [r for r, ss in vs if accepts(ss)]
    out[name] = {"units": len(vs), "accepted": len(acc), "share": round(len(acc) / len(vs), 3)}
    if name == "Matthew": out["matthew_verses"] = acc
    print(name, out[name], flush=True)
json.dump(out, open(H / "philo_control.json", "w"), ensure_ascii=False, indent=1)
