"""The open search: every stretch of a Greek text against every stretch of the non-biblical scrolls, through the bridge.

A Greek window is three verses; a scroll window is four consecutive lines of one fragment. A Greek word reaches a
scroll window when one of the scroll lexemes the bridge gives for it stands there. The score of a pair is the sum,
over the distinct scroll lexemes reached, of their weight log(N/df), where df counts the scroll windows holding
the lexeme; lexemes in more than 1.5 per cent of windows are not used. Matthew is compared with texts that run
through the same bridge: Mark, Luke, Revelation, and three Greek books outside the hypothesized system and of the
same period and idiom (1 Maccabees, Judith, Psalms of Solomon). Writes search.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
C = _CORP+"/"
sys.path.insert(0, str(H)); from bridge import gnorm, gfeats, hcons
B = {g: [lex for _, lex in v] for g, v in json.load(open(H / "bridge.json"))["bridge"].items()}
d = pickle.load(open(H / "dss_words.pkl", "rb")); lab = d["lab"]

# scroll windows (non-biblical lines only: words with no biblical book)
lines = collections.defaultdict(set)
for (sc, ln, b, c, v, g, bib, lang) in d["rows"]:
    if bib: continue
    lines[ln].add(hcons(g))
order = sorted(lines)                                  # node order = scroll order
wins = []
for i, ln in enumerate(order):
    s, fr, _ = lab[ln]; grp = [ln]
    for ln2 in order[i + 1:i + 4]:
        if lab[ln2][:2] == (s, fr): grp.append(ln2)
    wins.append((grp, set().union(*(lines[x] for x in grp))))
N = len(wins); df = collections.Counter()
for _, S in wins: df.update(S)
W = {lex: math.log(N / n) for lex, n in df.items() if n / N <= 0.015 and len(lex) >= 2}
def index(ws):
    iv = collections.defaultdict(list)
    for j, (_, S) in enumerate(ws):
        for lex in S:
            if lex in W: iv[lex].append(j)
    return iv
inv = index(wins)
# the null: windows of four lines drawn at random from anywhere in the non-biblical scrolls, as many as the real ones.
# Lines keep their own words; what is destroyed is the passage, four lines of one place together.
import random
rng = random.Random(0)
null_wins = [(None, set().union(*(lines[x] for x in rng.sample(order, 4)))) for _ in range(N)]
inv0 = index(null_wins)

def load_nt(book):
    out = []
    for l in open(C + f"gnt-nestle1904/text/{book}.txt", encoding="utf-8"):
        r, t = l.rstrip("\n").split("\t", 1); out.append((r.split(" ", 1)[1], t))
    return out
def load_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:
            r, t = l.rstrip("\n").split("\t", 1); m = re.search(r"(\d+:\d+)$", r)
            if m: out.append((m[1], t))
    return out
TEXTS = {"Matthew": load_nt("Matt"), "Mark": load_nt("Mark"), "Luke": load_nt("Luke"), "Revelation": load_nt("Rev"),
         "1 Maccabees": load_lxx("023"), "Judith": load_lxx("020"), "Psalms of Solomon": load_lxx("035")}

def lexemes_of(text):
    """Greek words of a window → {scroll lexeme: [greek words]}."""
    reach = collections.defaultdict(set)
    for w in set(re.findall(r"[α-ω]+", gnorm(text))):
        for f in gfeats(w):
            for lex in B.get(f, []):
                if lex in W: reach[lex].add(w)
    return reach

def run(name, verses, keep=0):
    best = []; pairs = []
    for i in range(len(verses)):
        span = verses[max(0, i - 1):i + 2]; text = " ".join(t for _, t in span)
        reach = lexemes_of(text); acc = collections.defaultdict(float); hit = collections.defaultdict(set)
        for lex in reach:
            for j in inv[lex]: acc[j] += W[lex]; hit[j].add(lex)
        top = sorted(((s, j) for j, s in acc.items() if len(hit[j]) >= 3), reverse=True)[:3]
        acc0 = collections.defaultdict(float); n0 = collections.Counter()
        for lex in reach:
            for j in inv0[lex]: acc0[j] += W[lex]; n0[j] += 1
        b0 = max([v for j, v in acc0.items() if n0[j] >= 3] or [1.0])
        b1 = top[0][0] if top else 0.0
        best.append(b1 / b0)
        if keep:
            for s, j in top[:1]:
                grp = wins[j][0]; a, z = lab[grp[0]], lab[grp[-1]]
                pairs.append({"greek": verses[i][0], "score": round(s, 2), "ratio_to_null": round(best[-1], 3), "scroll": a[0], "at": f"{a[1]}:{a[2]}–{z[2]}" if a[1] else f"{a[2]}–{z[2]}",
                              "lexemes": {lex: sorted(reach[lex]) for lex in hit[j]}})
    return best, pairs

out = {"scroll_windows": N, "lexemes_used": len(W), "texts": {}}
best = {}
for name, vs in TEXTS.items():
    b, p = run(name, vs, keep=(name == "Matthew"))
    best[name] = b
    if p: out["matthew_pairs"] = p
# the control threshold: the 99th percentile of the ratio (best real / best null) across the three outside books together
ctrl = sorted(x for n in ("1 Maccabees", "Judith", "Psalms of Solomon") for x in best[n])
T99 = ctrl[int(0.99 * len(ctrl))]; T95 = ctrl[int(0.95 * len(ctrl))]
for name, b in best.items():
    s = sorted(b)
    out["texts"][name] = {"windows": len(b), "median_ratio": round(s[len(s) // 2], 2), "over_T95": sum(x > T95 for x in b), "over_T99": sum(x > T99 for x in b),
                          "share_over_T99": round(sum(x > T99 for x in b) / len(b), 4)}
out["T95"], out["T99"] = round(T95, 2), round(T99, 2)
json.dump(out, open(H / "search.json", "w"), ensure_ascii=False, indent=1)
print(json.dumps({k: v for k, v in out.items() if k != "matthew_pairs"}, ensure_ascii=False, indent=1))
