"""M2, lemmas shared, on one instrument for every source (SCHEME.md §2; asked 2026-11-30 20:13).

The instrument is the expanded lemmas of #1812 XIII.1d as dss/thorough.py builds them, applied the same way to every text:
a word's family is its first five letters after a preverb is taken off (gkey); stop words are dropped (bridge.GSTOP).
  SAME/KIN  families present in both places;
  OPP       a family in one place whose fixed opposite (thorough.OPP) is in the other.
M2 for a row = distinct families shared, SAME/KIN and OPP together (OPP also reported alone).

Places. Matthew, Revelation and the letters: Nestle 1904 as seated. The Septuagint: Swete as seated, at the row's verse, with its
neighbours on either side (the window the x1 check used), best of the three. Philo: Cohn-Wendland as seated, the sections the
record names. Josephus: the row names a work and patterns, not a place; the places are those the sealed check found (three units
round each hit), and M2 is reported at the best place and at the first, since a name row's best place over many hits is inflated.
The scrolls are Hebrew and Aramaic: a Greek family of the Matthew place counts when the bridge (dss/bridge.json) links it to a Hebrew
family present in the named lines. That is a different instrument from the Greek-Greek count and is reported apart.
Writes m2.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, REVFIRST as _RF  # where the corpora are: see paths.py
import json, re, glob, pickle, collections, statistics, pathlib, sys
H = pathlib.Path(__file__).resolve().parent; UM = H.parent; C = _CORP+"/"
sys.path.insert(0, str(UM / "dss")); from bridge import gnorm, gfeats, hcons, GSTOP
from codes import F, EXCL
src = (UM / "dss/thorough.py").read_text(encoding="utf-8")
PRE = eval(re.search(r"PRE = (\[.*?\])", src, re.S).group(1)); OPP = eval(re.search(r"OPP = (\[.*?\])\nOPPMAP", src, re.S).group(1))
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
STEM = int(sys.argv[1]) if len(sys.argv) > 1 else 5    # 5: the family as thorough.py keys it; 4: four letters, word and deprefixed word both
def fams(t):
    ws = [w for w in re.findall(r"[α-ω]+", gnorm(t)) if w not in GSTOP and len(w) >= 3]
    return {deprefix(w)[:5] for w in ws} if STEM == 5 else {x[:4] for w in ws for x in (w, deprefix(w))}
def shared(a, b):
    A, B = fams(a), fams(b); same = A & B; opp = set()
    for x, y in OPP:
        for p, q in ((x, y), (y, x)):
            if any(f.startswith(p) for f in A) and any(f.startswith(q) for f in B): opp.add(p + "/" + q)
    return len(same), len(opp)
def load(path, key=lambda r: r):
    out = {}
    for l in open(path, encoding="utf-8"):
        if "\t" in l: r, t = l.rstrip("\n").split("\t", 1); out[key(r)] = t
    return out
NT = {}
for f in glob.glob(C + "gnt-nestle1904/text/*.txt"):
    b = pathlib.Path(f).stem; NT[b] = load(f, lambda r: tuple(int(x) for x in r.split(" ", 1)[1].split(":")))
BOOK = {"JAS": "Jas", "1PE": "1Pet", "2PE": "2Pet", "RO": "Rom", "GA": "Gal", "1CO": "1Cor", "2CO": "2Cor", "1TH": "1Thess", "2TH": "2Thess",
        "1TI": "1Tim", "2TI": "2Tim", "PHP": "Phil", "EPH": "Eph", "COL": "Col", "HEB": "Heb"}
def span(book, s):
    out = []
    for part in re.split(r"[;,]\s*", s):
        m = re.match(r"\s*(\d+):(\d+)(?:[-–](?:(\d+):)?(\d+))?", part)
        if not m: continue
        c, a = int(m.group(1)), int(m.group(2)); c2 = int(m.group(3)) if m.group(3) else c; z = int(m.group(4)) if m.group(4) else a
        out += [k for k in NT[book] if (c, a) <= k <= (c2, z)]
    return " ".join(NT[book][k] for k in out)
LXB = {"Gen": "001", "Exod": "002", "Lev": "003", "Num": "004", "Deut": "005", "4Kgdms": "014", "Ps": "027", "Hos": "036", "Mic": "038", "Zech": "046",
       "Mal": "047", "Isa": "048", "Jer": "049", "Dan": "057", "Sir": "034"}
LX = {b: list(load(glob.glob(C + f"lxx-swete/text/tlg{n}-*.txt")[0]).items()) for b, n in LXB.items()}
def lxx_best(mt, ref):
    b, cv = ref.split(); c, v = map(int, cv.split(":")); L = LX[b]
    idx = [i for i, (r, _) in enumerate(L) if re.search(rf"\b{c}:{v}$", r)]
    if not idx: return None
    i = idx[0]; return max(shared(mt, L[j][1]) for j in range(max(0, i - 1), min(len(L), i + 2)))
PHF = {"Leg.": ("002", 3), "Her.": ("015", 1), "Fug.": ("017", 1), "Conf.": ("013", 1), "Mut.": ("018", 1), "Spec.": ("024", None), "Decal.": ("023", 1)}
def philo_text(ref):
    out = []
    for m in re.finditer(r"(Leg\.|Her\.|Fug\.|Conf\.|Mut\.|Spec\.|Decal\.)\s*([\d.,\s\-–]+)", ref):
        work, nums = m.group(1), m.group(2); n, book = PHF[work]
        rows = [l.rstrip("\n").split("\t", 1) for l in open(glob.glob(C + f"philo/text/tlg{n}-*.txt")[0], encoding="utf-8") if "\t" in l]
        blocks, cur, last = [], [], 0
        for r, t in rows:
            s = int(re.search(r"(\d+)$", r).group(1))
            if s < last: blocks.append(cur); cur = []
            cur.append((s, t)); last = s
        blocks.append(cur)
        for part in re.split(r",\s*", nums.strip()):
            mm = re.match(r"(?:(\d+)\.)?(\d+)(?:[-–](\d+))?", part.strip())
            if not mm: continue
            bk = int(mm.group(1)) if mm.group(1) else (book or 1); a = int(mm.group(2)); z = int(mm.group(3) or a)
            blk = blocks[bk - 1] if bk - 1 < len(blocks) else blocks[0]
            out += [t for s, t in blk if a <= s <= z]
    return " ".join(out)
# Josephus places: re-run the sealed check's search (notebook scripts/bj.py) and keep its places
bj = open(_RF+"/notebook/scripts/bj.py", encoding="utf-8").read()
ns = {}; exec(bj.split("def has(t,keys)")[0], ns)
J, JROWS = ns["J"], ns["ROWS"]
def has(t, keys): return all(re.search(k, t) for k in keys)
def jplaces(w, keys):
    U_ = J[w]; out = []
    for i in range(len(U_)):
        t = " ".join(x[1] for x in U_[max(0, i - 1):i + 2])
        if has(t, keys): out.append(" ".join(x[1] for x in U_[max(0, i - 1):i + 2]))
    return out
# the scrolls
d = pickle.load(open(UM / "dss/dss_words.pkl", "rb")); lab = d["lab"]
lines = collections.defaultdict(set)
for (sc, ln, b, c, v, g, bib, lang) in d["rows"]: lines[ln].add(hcons(g))
BR = {g: [lex for _, lex in v] for g, v in json.load(open(UM / "dss/bridge.json"))["bridge"].items()}
def scroll_lines(ref):
    m = re.match(r"(\S+)\s+(.+)", ref); sc, loc = m.group(1), m.group(2)
    out = set()
    for part in re.split(r"[;,]|\(and ", loc):
        mm = re.search(r"([\w+]+):(\d+)(?:-(?:([\w+]+):)?(\d+))?", part)
        if not mm: continue
        col, a = mm.group(1), int(mm.group(2)); col2 = mm.group(3) or col; z = int(mm.group(4) or a)
        for ln, (s, fr, li) in lab.items():
            if s != sc: continue
            try: li = int(li)
            except ValueError: continue
            if (fr == col and (a <= li <= (z if col2 == col else 999))) or (col2 != col and fr == col2 and li <= z): out |= lines[ln]
    return out
def scroll_m2(mt, ref):
    heb = scroll_lines(ref)
    if not heb: return None
    hit = set()
    for w in set(re.findall(r"[α-ω]+", gnorm(mt))):
        for f in gfeats(w) | gfeats(deprefix(w)):
            if any(lex in heb for lex in BR.get(f, [])): hit.add(deprefix(w)[:5])
    return len(hit)

import random
MK = sorted(NT["Matt"]); random.seed(20261130)
def nverses(s): return max(1, len(span("Matt", s).split(" ")) // 18)
def exchanged(srctext, mt, k=20):
    """the same source place against k Matthew spans of the same length in words, drawn at random: the baseline for this row"""
    n = len(mt.split()); out = []
    for _ in range(k):
        i = random.randrange(len(MK)); words = []
        j = i
        while len(words) < n and j < len(MK): words += NT["Matt"][MK[j]].split(); j += 1
        a, o = shared(" ".join(words[:n]), srctext); out.append(a + o)
    return statistics.mean(out)
inv = {r["id"]: r for r in json.load(open(H / "rows.inventory.json"))}
res = {}
for i, r in inv.items():
    if i in EXCL: continue
    mt = span("Matt", r["matt"]); s = r["source"]
    st = None
    if s == "Revelation": st = span("Rev", r["src_ref"][4:]); v = shared(mt, st)
    elif s == "letters": st = " ".join(span(BOOK[b], sp) for b, sp in (p.split(" ", 1) for p in r["src_ref"].split("; "))); v = shared(mt, st)
    elif s.startswith("Septuagint"):
        v = lxx_best(mt, r["src_ref"]); b_, cv = r["src_ref"].split(); c_, v_ = map(int, cv.split(":"))
        st = next((t for rr, t in LX[b_] if re.search(rf"\b{c_}:{v_}$", rr)), None)
    elif s.startswith("Philo"): st = philo_text(r["src_ref"]); v = shared(mt, st)
    elif s == "Josephus":
        row = [x for x in JROWS if x[0] == r["matt"] and x[4] == r["src_text"]][0]; pl = jplaces(row[1], row[2])
        vals = [shared(mt, t) for t in pl]; v = max(vals, key=lambda x: x[0] + x[1]) if vals else None
        res[i] = {"source": s, "best": v, "first": vals[0] if vals else None, "places": len(pl), "base_first": round(exchanged(pl[0], mt), 2) if pl else None}; continue
    elif s == "scrolls":
        bm = scroll_m2(mt, r["src_ref"]); bb = None
        if bm is not None:
            n = len(mt.split()); vals = []
            for _ in range(20):
                k = random.randrange(len(MK)); words = []; j = k
                while len(words) < n and j < len(MK): words += NT["Matt"][MK[j]].split(); j += 1
                vals.append(scroll_m2(" ".join(words[:n]), r["src_ref"]))
            bb = round(statistics.mean(vals), 2)
        res[i] = {"source": s, "bridge": bm, "base": bb}; continue
    res[i] = {"source": s, "same": v[0] if v else None, "opp": v[1] if v else None, "base": round(exchanged(st, mt), 2) if st else None}
json.dump(res, open(H / f"m2-stem{STEM}.json", "w"), ensure_ascii=False, indent=0)
SRC = ["Septuagint, named", "Septuagint, tacit", "Revelation", "Philo, with Revelation", "letters", "Josephus", "scrolls"]
for s in SRC:
    xs = [v for v in res.values() if v["source"] == s]
    if s == "Josephus":
        b = [x["best"][0] + x["best"][1] for x in xs if x["best"]]; f = [x["first"][0] + x["first"][1] for x in xs if x["first"]]
        bf = [x["first"][0] + x["first"][1] - x["base_first"] for x in xs if x["first"] and x.get("base_first") is not None]
        print(f"{s:24} n={len(xs):3}  best place median {statistics.median(b)}  first place median {statistics.median(f)}  (places per row median {statistics.median([x['places'] for x in xs])})  first place over exchanged baseline: median {statistics.median(bf):+.2f}")
    elif s == "scrolls":
        b = [x["bridge"] for x in xs if x["bridge"] is not None]
        bb = [x["bridge"] - x["base"] for x in xs if x["bridge"] is not None]
        print(f"{s:24} n={len(xs):3}  bridge families median {statistics.median(b)}  (lines found for {len(b)} of {len(xs)})  over exchanged baseline: median {statistics.median(bb):+.2f}")
    else:
        a = [x["same"] + x["opp"] for x in xs if x["same"] is not None]; o = [x["opp"] for x in xs if x["opp"] is not None]
        bb = [x["same"] + x["opp"] - x["base"] for x in xs if x.get("base") is not None]
        print(f"{s:24} n={len(xs):3}  M2 median {statistics.median(a)}  (OPP alone median {statistics.median(o)}; places read {len(a)} of {len(xs)})" + (f"  over exchanged baseline: median {statistics.median(bb):+.2f}" if bb else ""))
