"""The thorough search: every three verses of Matthew against every four lines of the non-biblical scrolls,
through the bridge, with the expanded lemmas, under a strict rule fixed before the run, and with controls.

Expanded lemmas, as #1812 XIII.1d names them, applied the same way to every Greek text:
  SAME  the word's own stems;
  KIN   the stems of the word with its preverb taken off (ἐκ-βάλλω, βάλλω), so a compound meets its simple verb,
        and on the Hebrew side one family for a lexeme and its derived nouns (ברך, ברכה; שפט, משפט);
  OPP   a word also reaches the scroll lexemes of its opposite, from a fixed list of opposed families.
FIELD is not used: it did not tell true pairs from false ones (#1812 XIII.1d).

The rule (strict), sealed in this docstring before the run:
  a Greek window and a scroll window are joined when they share links to at least three distinct Greek families
  and three distinct Hebrew families, and either one link is rare on both sides (the Greek family in 20 New
  Testament verses or fewer, the Hebrew family in 0.3 per cent of scroll windows or fewer), or two links are
  moderately rare on both sides (60 verses or fewer; 1 per cent or fewer). OPP links count, and are marked.
A verse of Matthew is reached when the window centred on it is joined to some scroll window.
Controls, run through the identical rule: Mark, Luke, Revelation (inside the system); 1 Maccabees (Septuagint
Greek, a Jewish book of the period, not hypothesized as Matthew's source); Epictetus's Discourses (Koine,
outside the Jewish world). Writes thorough.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, pickle, re, math, glob, collections, pathlib, sys
H = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(H)); from bridge import gnorm, gfeats, hcons
C = _CORP+"/"
B = {g: [lex for _, lex in v] for g, v in json.load(open(H / "bridge.json"))["bridge"].items()}

PRE = ["συν", "συμ", "συγ", "συλ", "απο", "αφ", "επι", "εφ", "κατα", "καθ", "κατ", "ανα", "δια", "εκ", "εξ", "εισ", "εν", "εμ", "περι",
       "προσ", "προ", "υπο", "υφ", "υπερ", "παρα", "παρ", "μετα", "μεθ", "μετ", "αντι", "ανθ"]
def deprefix(w):
    for p in sorted(PRE, key=len, reverse=True):
        if w.startswith(p) and len(w) - len(p) >= 4: return w[len(p):]
    return w
def gkey(w): return deprefix(w)[:5]                       # the Greek family of a word
def hfam(x):                                              # the Hebrew family of a scroll lexeme
    if len(x) >= 4 and x[0] in "מת": x = x[1:]
    if len(x) >= 4 and x[-1] in "הת": x = x[:-1]
    return x
OPP = [("πρωτ", "εσχατ"), ("δεσ", "λυσ"), ("δεω", "λυω"), ("πλουσ", "πτωχ"), ("αγαπ", "μισ"), ("φωσ", "σκοτ"), ("φωτ", "σκοτ"), ("υψο", "ταπειν"),
       ("μεγα", "μικρ"), ("ανοιγ", "κλει"), ("ζω", "θαν"), ("ζωη", "θανατ"), ("δικαι", "αδικ"), ("δικαι", "ανομ"), ("καθαρ", "ακαθαρ"), ("ευλογ", "καταρ"),
       ("σοφ", "μωρ"), ("ημερ", "νυκτ"), ("δουλ", "κυρι"), ("δεξι", "αριστερ"), ("δεξι", "ευωνυμ"), ("ειρην", "μαχαιρ"), ("ειρην", "πολεμ"), ("αληθ", "ψευδ"),
       ("φιλ", "εχθρ"), ("αγαθ", "πονηρ"), ("αγαθ", "κακ"), ("τυφλ", "βλεπ"), ("εισερχ", "εξερχ"), ("κρυπτ", "φανερ"), ("δοξ", "ατιμ"), ("χαρ", "λυπ"),
       ("πεινα", "χορτα"), ("διδω", "λαμβ"), ("σπειρ", "θεριζ"), ("οικοδομ", "καταλυ"), ("συναγ", "σκορπ")]
OPPMAP = collections.defaultdict(set)
for a, b in OPP:
    for x, y in ((a, b), (b, a)):
        OPPMAP[x] |= {f for f in B if f.startswith(y)}
def links_of(text):
    """Greek words of a window → list of (greek family, hebrew lexeme family, level)."""
    out = set()
    for w in set(re.findall(r"[α-ω]+", gnorm(text))):
        same = gfeats(w); kin = gfeats(deprefix(w)) - same
        for lvl, feats in (("SAME", same), ("KIN", kin)):
            for f in feats:
                for lex in B.get(f, []): out.add((gkey(w), hfam(lex), lvl))
        for p, opp in OPPMAP.items():
            if w.startswith(p):
                for f in opp:
                    for lex in B.get(f, []): out.add((gkey(w), hfam(lex), "OPP"))
    return out

# New Testament verse frequency of Greek families
NTDF = collections.Counter(); NV = 0
for f in glob.glob(C + "gnt-nestle1904/text/*.txt"):
    for l in open(f, encoding="utf-8"):
        NV += 1; NTDF.update({gkey(w) for w in re.findall(r"[α-ω]+", gnorm(l.split("\t", 1)[1]))})

# scroll windows as Hebrew families
d = pickle.load(open(H / "dss_words.pkl", "rb")); lab = d["lab"]
lines = collections.defaultdict(set)
for (sc, ln, b, c, v, g, bib, lang) in d["rows"]:
    if not bib: lines[ln].add(hfam(hcons(g)))
order = sorted(lines); wins = []
for i, ln in enumerate(order):
    s, fr, _ = lab[ln]; grp = [ln] + [x for x in order[i + 1:i + 4] if lab[x][:2] == (s, fr)]
    wins.append((grp, set().union(*(lines[x] for x in grp))))
N = len(wins); HDF = collections.Counter()
for _, S in wins: HDF.update(S)
inv = collections.defaultdict(list)
for j, (_, S) in enumerate(wins):
    for h in S:
        if HDF[h] / N <= 0.015 and len(h) >= 2: inv[h].append(j)

def judge(links_here):
    gs = {g for g, _, _ in links_here}; hs = {h for _, h, _ in links_here}
    if len(gs) < 3 or len(hs) < 3: return False
    rare = [(g, h) for g, h, _ in links_here if NTDF[g] <= 20 and HDF[h] / N <= 0.003]
    mod = {(g, h) for g, h, _ in links_here if NTDF[g] <= 60 and HDF[h] / N <= 0.01}
    return bool(rare) or len({g for g, _ in mod}) >= 2 and len({h for _, h in mod}) >= 2

def search(text):
    L = links_of(text); byh = collections.defaultdict(list)
    for g, h, lvl in L: byh[h].append((g, h, lvl))
    cand = collections.defaultdict(list)
    for h, lst in byh.items():
        for j in inv.get(h, []): cand[j] += lst
    best = None
    for j, lk in cand.items():
        if len({x[1] for x in lk}) < 3: continue
        if judge(lk):
            sc = sum(math.log(N / HDF[h]) for h in {x[1] for x in lk})
            if best is None or sc > best[0]: best = (sc, j, lk)
    return best

def windows_from_verses(vs):
    return [(vs[i][0], " ".join(t for _, t in vs[max(0, i - 1):i + 2])) for i in range(len(vs))]
def windows_from_words(text, size=55):
    w = text.split(); return [(f"w{i}", " ".join(w[max(0, i - size // 2):i + size // 2])) for i in range(0, len(w), size)]
def nt(book):
    return [(l.split("\t", 1)[0].split(" ", 1)[1], l.rstrip("\n").split("\t", 1)[1]) for l in open(C + f"gnt-nestle1904/text/{book}.txt", encoding="utf-8")]
def lxx(n):
    out = []
    for l in open(glob.glob(C + f"lxx-swete/text/tlg{n}-*.txt")[0], encoding="utf-8"):
        if "\t" in l: out.append(tuple(l.rstrip("\n").split("\t", 1)))
    return out
EPI = " ".join(l.strip() for l in open(C + "epictetus-dissertationes-schenkl-1916/text/dissertationes.txt", encoding="utf-8") if not l.startswith("["))
TEXTS = {"Matthew": windows_from_verses(nt("Matt")), "Mark": windows_from_verses(nt("Mark")), "Luke": windows_from_verses(nt("Luke")),
         "Revelation": windows_from_verses(nt("Rev")), "1 Maccabees": windows_from_verses(lxx("023")), "Epictetus": windows_from_words(EPI)}

def best_score(text):
    """The strongest join of a Greek window to any scroll window: over distinct Hebrew families, the weight of the
    rarest Greek family linked to each plus the Hebrew family's own weight. At least three families each side."""
    L = links_of(text); byh = collections.defaultdict(list)
    for g, h, lvl in L: byh[h].append((g, h, lvl))
    cand = collections.defaultdict(list)
    for h, lst in byh.items():
        for j in inv.get(h, []): cand[j] += lst
    best = (0.0, None, None)
    for j, lk in cand.items():
        hs = {}
        for g, h, lvl in lk:
            w = math.log(N / HDF[h]) + math.log(NV / (1 + NTDF[g]))
            if w > hs.get(h, (0,))[0]: hs[h] = (w, g)
        if len(hs) < 3 or len({g for _, g in hs.values()}) < 3: continue
        sc = sum(w for w, _ in hs.values())
        if sc > best[0]: best = (sc, j, lk)
    return best

if len(sys.argv) > 1 and sys.argv[1] == "calibrated":
    res = {}
    for name, ws in TEXTS.items():
        res[name] = [(ref,) + best_score(text) for ref, text in ws]
        print(name, "done", flush=True)
    ctrl = sorted(x[1] for x in res["Epictetus"])
    T = {q: ctrl[int(q * len(ctrl)) - 1] for q in (0.95, 0.99)}
    out = {"thresholds_from_epictetus": {str(k): round(v, 2) for k, v in T.items()}, "texts": {}, "matthew": {}}
    for name, rs in res.items():
        out["texts"][name] = {"windows": len(rs), "over_95": sum(x[1] > T[0.95] for x in rs), "over_99": sum(x[1] > T[0.99] for x in rs),
                              "share_95": round(sum(x[1] > T[0.95] for x in rs) / len(rs), 3), "share_99": round(sum(x[1] > T[0.99] for x in rs) / len(rs), 3)}
        print(name, out["texts"][name])
    for ref, sc, j, lk in res["Matthew"]:
        if j is None: continue
        grp = wins[j][0]; a, z = lab[grp[0]], lab[grp[-1]]
        out["matthew"][ref] = {"score": round(sc, 1), "over_95": sc > T[0.95], "over_99": sc > T[0.99], "scroll": a[0],
                               "at": f"{a[1]}:{a[2]}–{z[2]}" if a[1] else f"{a[2]}–{z[2]}", "links": sorted({f"{g}→{h} ({lvl})" for g, h, lvl in lk})}
    json.dump(out, open(H / "thorough_calibrated.json", "w"), ensure_ascii=False, indent=1)
    sys.exit()

out = {"rule": __doc__.split("The rule (strict), sealed in this docstring before the run:")[1].split("A verse of Matthew")[0].strip(),
       "scroll_windows": N, "texts": {}, "matthew": {}}
for name, ws in TEXTS.items():
    acc = 0
    for ref, text in ws:
        b = search(text)
        if b:
            acc += 1
            if name == "Matthew":
                sc, j, lk = b; grp = wins[j][0]; a, z = lab[grp[0]], lab[grp[-1]]
                out["matthew"][ref] = {"scroll": a[0], "at": f"{a[1]}:{a[2]}–{z[2]}" if a[1] else f"{a[2]}–{z[2]}", "score": round(sc, 1),
                                       "links": sorted({f"{g}→{h} ({lvl})" for g, h, lvl in lk})}
    out["texts"][name] = {"windows": len(ws), "joined": acc, "share": round(acc / len(ws), 3)}
    print(name, out["texts"][name], flush=True)
json.dump(out, open(H / "thorough.json", "w"), ensure_ascii=False, indent=1)
