"""A Greek→Hebrew bridge into the scrolls' own vocabulary, learned in two steps from texts in the seats.

1. Greek → Hebrew lemma (Strong's number): the Septuagint (Swete) aligned verse by verse with the Masoretic
   text (WLC, OSHB lemmas), over the books whose numbering the two share.
2. Hebrew lemma → scroll lexeme: the WLC aligned with the biblical scrolls (Abegg–Bowley–Cook lexemes) at
   the same verses, which ties each lemma to the lexeme the scrolls use for it.
Association is Dice over aligned verses. Greek words are reduced to two stems (four and five letters);
both are used, so a short word and its inflections meet. Writes bridge.json: Greek stem → scroll lexemes.
"""
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, glob, collections, unicodedata as U, pathlib
H = pathlib.Path(__file__).resolve().parent
C = _CORP+"/"
FIN = str.maketrans("ךםןףץ", "כמנפצ")
def hcons(s):
    return "".join(c for c in U.normalize("NFD", s) if "א" <= c <= "ת").translate(FIN)
def gnorm(t):
    t = U.normalize("NFD", t); return "".join(c for c in t if not U.combining(c)).lower().replace("ς", "σ")
GSTOP = set(("και δε ο η το του τησ τω τη των τοισ ταισ τον την τα οι αι εν εισ εκ εξ επι προσ απο δια μετα κατα υπο υπερ περι παρα "
             "ου ουκ ουχ μη γαρ οτι ωσ ινα εαν αν οσ ητισ τι τισ αυτοσ αυτου αυτω αυτον αυτη αυτησ αυτων αυτοισ αυτουσ αυτα εγω μου μοι με "
             "συ σου σοι σε ημεισ ημων ημιν ημασ υμεισ υμων υμιν υμασ ουτοσ τουτο ταυτα τουτου τουτω εκεινοσ εκεινου εστιν ην ησαν ειναι εσται "
             "εστε εισιν ειμι εγενετο ουν αλλα ουδε μηδε ουτωσ τοτε ιδου").split())
def gfeats(w):
    if w in GSTOP or len(w) < 3: return set()
    return {w[:4], w[:5]} if len(w) >= 5 else {w[:4]}
def gset(t):
    out = set()
    for w in re.findall(r"[α-ω]+", gnorm(t)): out |= gfeats(w)
    return out

SW = {"Gen": "001", "Exod": "002", "Lev": "003", "Num": "004", "Deut": "005", "Josh": "006", "Judg": "008", "Ruth": "010", "1Sam": "011",
      "2Sam": "012", "1Kgs": "013", "2Kgs": "014", "1Chr": "015", "2Chr": "016", "Ps": "027", "Song": "031", "Job": "032", "Hos": "036",
      "Amos": "037", "Mic": "038", "Joel": "039", "Obad": "040", "Jonah": "041", "Nah": "042", "Hab": "043", "Zeph": "044", "Hag": "045",
      "Zech": "046", "Mal": "047", "Isa": "048", "Lam": "051", "Ezek": "053", "Dan": "057"}
DSSB = {"Gen": "Gen", "Ex": "Exod", "Lev": "Lev", "Num": "Num", "Deut": "Deut", "Josh": "Josh", "Judg": "Judg", "Ruth": "Ruth", "1Sam": "1Sam",
        "2Sam": "2Sam", "1Kgs": "1Kgs", "2Kgs": "2Kgs", "Ps": "Ps", "Song": "Song", "Job": "Job", "Hos": "Hos", "Amos": "Amos", "Mic": "Mic",
        "Joel": "Joel", "Obad": "Obad", "Jonah": "Jonah", "Nah": "Nah", "Hab": "Hab", "Zeph": "Zeph", "Hag": "Hag", "Zech": "Zech", "Mal": "Mal",
        "Is": "Isa", "Lam": "Lam", "Ezek": "Ezek", "Dan": "Dan", "Prov": "Prov", "Eccl": "Eccl", "Jer": "Jer", "Ezra": "Ezra", "2Chr": "2Chr"}
def lxxkey(b, c, v):
    if b == "Ps" and 11 <= c <= 146: c -= 1
    return (b, c, v)

LXX = {}
for b, n in SW.items():
    for l in open(glob.glob(C + f"lxx-swete/text/tlg{n}-*.txt")[0], encoding="utf-8"):
        if "\t" not in l: continue
        r, t = l.rstrip("\n").split("\t", 1); m = re.search(r"(\d+):(\d+)$", r)
        if m: LXX[(b, int(m[1]), int(m[2]))] = gset(t)
WLC = {}
for f in glob.glob(C + "hebrew-wlc/original/*.xml"):
    x = open(f, encoding="utf-8").read()
    for vm in re.finditer(r'<verse osisID="([^"]+)"[^>]*>(.*?)</verse>', x, re.S):
        b, c, v = vm[1].split("."); lem = set()
        for lm in re.findall(r'lemma="([^"]+)"', vm[2]):
            for p in lm.split("/"):
                p = p.strip().split(" ")[0]
                if p.isdigit(): lem.add(p)
        WLC[(b, int(c), int(v))] = lem

def dice_table(pairs, minn, mind, topk):
    ca, cb, cab = collections.Counter(), collections.Counter(), collections.Counter()
    for A, B in pairs:
        ca.update(A); cb.update(B)
        for a in A:
            for b in B: cab[(a, b)] += 1
    best = collections.defaultdict(list)
    for (a, b), n in cab.items():
        if n >= minn:
            dz = 2 * n / (ca[a] + cb[b])
            if dz >= mind: best[a].append((round(dz, 3), b, n))
    return {a: sorted(v, reverse=True)[:topk] for a, v in best.items()}, ca, cb

def main():
    p1 = [(LXX[lxxkey(*k)], WLC[k]) for k in WLC if lxxkey(*k) in LXX and k[0] in SW]
    g2s, cg, cs = dice_table(p1, 4, 0.15, 4)

    d = pickle.load(open(H / "dss_words.pkl", "rb"))
    DV = collections.defaultdict(set)
    for (sc, ln, b, c, v, g, bib, lang) in d["rows"]:
        if b in DSSB and c and v:
            try: DV[(DSSB[b], int(c), int(v))].add(hcons(g))
            except ValueError: pass
    p2 = [(WLC[k], DV[k]) for k in DV if k in WLC]
    s2l, _, _ = dice_table(p2, 3, 0.3, 2)

    bridge = {}
    for g, lst in g2s.items():
        out = {}
        for dz, s, n in lst:
            for dz2, lex, n2 in s2l.get(s, []):
                out[lex] = max(out.get(lex, 0), round(dz * dz2, 3))
        if out: bridge[g] = sorted(((v, k) for k, v in out.items()), reverse=True)[:4]
    json.dump({"step1_verses": len(p1), "step2_verses": len(p2), "bridge": bridge}, open(H / "bridge.json", "w"), ensure_ascii=False)
    print(len(p1), "LXX–WLC verses;", len(p2), "WLC–scroll verses;", len(bridge), "Greek stems bridged")
    for g in ["αρτο", "ευλογ", "ποτη", "αμπε", "διαθ", "ποιμ", "προβ", "οινο", "εχθρ", "μισε", "θρον", "αγαπ", "τραπ", "καθη", "πρωτ", "δωδε", "φυλη", "κριν", "νεκρ", "τυφλ", "πτωχ", "καιν", "πολλ", "δεξι", "δοξα"]:
        print(g, bridge.get(g, [])[:3])

if __name__ == "__main__":
    main()
