"""Calibration of the open search on the sealed rows that hold: for each row, where does the scroll place it names
rank among all scroll windows, as seen from its Matthew verses? Variants of the instrument are compared on
alternate rows (odd rows to choose, even rows to report), so the choice is not scored on the rows that made it."""
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, 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()}
chk = json.load(open(H / "check.json")); held = [r for r in chk["rows"] if r["holds"]]
held += [dict(r, hebrew_at=c["at"]) for c in chk["corrections"] for r in chk["rows"] if (r["matt"], r["scroll"]) == (c["matt"], c["scroll"]) and c["holds"]]
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(hcons(g))
order = sorted(lines)
MT = {}
for l in open(C + "gnt-nestle1904/text/Matt.txt", encoding="utf-8"):
    r, t = l.rstrip("\n").split("\t", 1); MT[r.split(" ", 1)[1]] = gnorm(t)
# Greek document frequency over the New Testament verses
import glob
gdf = collections.Counter(); NV = 0
for f in glob.glob(C + "gnt-nestle1904/text/*.txt"):
    for l in open(f, encoding="utf-8"):
        NV += 1; gdf.update(set(re.findall(r"[α-ω]+", gnorm(l.split("\t", 1)[1]))))
def gidf(w): return math.log(NV / (1 + gdf[w]))

def build(win):
    wins = []
    for i, ln in enumerate(order):
        s, fr, _ = lab[ln]; grp = [ln]
        for ln2 in order[i + 1:i + win]:
            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)
    return wins, N, df

def mverses(spec):
    out = []
    for part in re.split(r";\s*", spec):
        m = re.match(r"(\d+):(\d+)(?:-(\d+))?", part.strip()); c, a, z = int(m[1]), int(m[2]), int(m[3] or m[2])
        out += [f"{c}:{v}" for v in range(a, z + 1) if f"{c}:{v}" in MT]
    return out

def ranks(win, cap, greek_weight, minlex):
    wins, N, df = build(win)
    W = {lex: math.log(N / n) for lex, n in df.items() if n / N <= cap}
    inv = collections.defaultdict(list)
    for j, (_, S) in enumerate(wins):
        for lex in S:
            if lex in W: inv[lex].append(j)
    out = []
    for r in held:
        text = " ".join(MT[v] for v in mverses(r["matt"]))
        reach = collections.defaultdict(float)
        for w in set(re.findall(r"[α-ω]+", text)):
            gw = gidf(w) if greek_weight else 1.0
            for f in gfeats(w):
                for lex in B.get(f, []):
                    if lex in W: reach[lex] = max(reach[lex], gw)
        acc = collections.defaultdict(float); n = collections.Counter()
        for lex, gw in reach.items():
            for j in inv[lex]: acc[j] += W[lex] * gw; n[j] += 1
        target_scroll = r["scroll"]; at = r["hebrew_at"].split("–")[0]
        tj = [j for j, (grp, _) in enumerate(wins) if lab[grp[0]][0] == target_scroll and
              (f"{lab[grp[0]][1]}:{lab[grp[0]][2]}" if lab[grp[0]][1] else lab[grp[0]][2]) == at]
        sc = sorted((v for j, v in acc.items() if n[j] >= minlex), reverse=True)
        t = max([acc.get(j, 0) for j in tj] or [0])
        out.append(1 + sum(1 for v in sc if v > t))
    return out

if __name__ == "__main__":
    res = {}
    for win in (4, 6):
        for cap in (0.015, 0.05):
            for gw in (False, True):
                rk = ranks(win, cap, gw, 2)
                odd, even = rk[1::2], rk[0::2]
                med = lambda x: sorted(x)[len(x) // 2]
                res[f"win{win}_cap{cap}_greekidf{gw}"] = {"median_rank_odd": med(odd), "median_rank_even": med(even), "top100_even": sum(x <= 100 for x in even), "n_even": len(even)}
                print(win, cap, gw, res[f"win{win}_cap{cap}_greekidf{gw}"])
    json.dump(res, open(H / "calibrate.json", "w"), indent=1)

order_ix = {ln: i for i, ln in enumerate(order)}
def reading_list(win=6, cap=0.015, k=5):
    """For each three-verse stretch of Matthew, the k scroll windows the calibrated instrument ranks highest."""
    wins, N, df = build(win)
    W = {lex: math.log(N / n) for lex, n in df.items() if n / N <= cap}
    inv = collections.defaultdict(list)
    for j, (_, S) in enumerate(wins):
        for lex in S:
            if lex in W: inv[lex].append(j)
    keys = list(MT); out = []
    for i, v in enumerate(keys):
        text = " ".join(MT[x] for x in keys[max(0, i - 1):i + 2])
        reach = collections.defaultdict(float); words = collections.defaultdict(set)
        for w in set(re.findall(r"[α-ω]+", text)):
            for f in gfeats(w):
                for lex in B.get(f, []):
                    if lex in W: reach[lex] = max(reach[lex], gidf(w)); words[lex].add(w)
        acc = collections.defaultdict(float); hit = collections.defaultdict(set)
        for lex, gw in reach.items():
            for j in inv[lex]: acc[j] += W[lex] * gw; hit[j].add(lex)
        ranked = sorted(((s, j) for j, s in acc.items() if len(hit[j]) >= 2), reverse=True)
        top, seen = [], []
        for s, j in ranked:                      # distinct places: no two windows of one fragment within six lines
            sc, fr, _ = lab[wins[j][0][0]]; pos = order_ix[wins[j][0][0]]
            if any(sc == a and fr == b and abs(pos - p) < 6 for a, b, p in seen): continue
            seen.append((sc, fr, pos)); top.append((s, j))
            if len(top) == k: break
        out.append({"matt": v, "candidates": [{"score": round(s, 1), "scroll": lab[wins[j][0][0]][0],
                    "at": "%s:%s–%s" % (lab[wins[j][0][0]][1], lab[wins[j][0][0]][2], lab[wins[j][0][-1]][2]),
                    "via": {lex: sorted(words[lex]) for lex in hit[j]}} for s, j in top]})
    json.dump(out, open(H / "reading_list.json", "w"), ensure_ascii=False)
    return out
