"""The challenge, searched. Every window of five consecutive units (verses or sections) in the seated Septuagint, Philo and Josephus
is scored for the nine members of the configuration fixed in ../rev/rev_rows_sealed.py (sealed 2026-12-01T01:57:18Z), by word.
A window enters only if it has bread with wine or a cup (F3) and a blessing or thanksgiving (F4). The top windows are then read.
A lexical finder: it proposes, a reader decides. 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 re, json, pathlib, unicodedata as U
C = pathlib.Path(_CORP+"")
def g(t):
    t = U.normalize("NFD", t); return "".join(c for c in t if not U.combining(c)).lower().replace("ς", "σ")
F = {"F1": r"\bδωδεκα|\bδεκα\b|συναγωγ|εκκλησι|συστημα|πληθοσ",
     "F2": r"εσπερ|νυκτ|πασχα|εορτ|οψια",
     "F3": None,
     "F4": r"ευλογ|ευχαριστ|ευχη|ευχομ|προκατευχ|επευχ",
     "F5": r"χριστ|μεσσια|ηλειμμεν",
     "F6": r"χειρ",
     "F7": r"ταξει|ταξιν|πρωτοκλισ|κατακλισ|εισκρισ|πρεσβυτερ|πρωτοκαθεδρ",
     "F8": r"εσχατ|εν τη ημερα εκεινη|βασιλεια",
     "F9": r"διαθηκ|πολλων"}
def f3(t): return bool(re.search(r"αρτ[οωευ]", t) and re.search(r"οιν[οωευ]|ποτηρι|γλευκ", t))
units = []
for f in sorted((C / "lxx-swete/text").glob("*.txt")) + sorted((C / "philo/text").glob("*.txt")) + sorted((C / "josephus/text").glob("*.txt")):
    for l in open(f, encoding="utf-8"):
        if "\t" in l:
            r, t = l.rstrip("\n").split("\t", 1); units.append((f.stem, r, g(t)))
hits = []
for i in range(len(units) - 4):
    W = units[i:i + 5]
    if W[0][0] != W[-1][0]: continue
    t = " ".join(x[2] for x in W)
    if not f3(t) or not re.search(F["F4"], t): continue
    s = {k: (f3(t) if k == "F3" else bool(re.search(p, t))) for k, p in F.items()}
    hits.append({"book": W[0][0], "from": W[0][1], "to": W[-1][1], "score": sum(s.values()), "features": [k for k, v in s.items() if v]})
best = {}
for h in sorted(hits, key=lambda h: -h["score"]):
    k = (h["book"], h["from"].rsplit(".", 1)[0] if "." in h["from"] else h["from"].split(":")[0])
    best.setdefault(k, h)
top = sorted(best.values(), key=lambda h: -h["score"])
json.dump({"windows_gated": len(hits), "top": top[:40]}, open("search.json", "w"), ensure_ascii=False, indent=1)
print(len(units), "units;", len(hits), "windows pass the gate")
for h in top[:25]: print(h["score"], h["book"], h["from"], "–", h["to"], h["features"])
