#!/usr/bin/env python3
"""VMS token predictor: the language-model idea applied to the manuscript itself.

Interpolated Kneser-Ney trigram over EVA words (ZL IVTFF 2b), plus a char
trigram for words the word model has never seen. Every folio is scored
leave-one-folio-out, so a page is predicted only from the rest of the book.

  vms_predict.py rank                 per-folio bits/word, top-1/top-5, joined to substrate weight
  vms_predict.py folio f57v [--n 15]  the tokens on a page that most break the model
  vms_predict.py next f57v.4 6 [--k 8] top-k guesses for word 6 of a line, with the folios that taught each one
"""
import re, sys, math, json, sqlite3, argparse, collections
ZL = 'c7ffff9e1f3ecbec174e234c.txt'
DB = '../../../resources/tools/substrate/index.html'
BOS, EOS = '<s>', '</s>'

def clean(t):
    t = re.sub(r'<![^>]*>', '', t); t = re.sub(r'<[^>]*>', '', t)
    t = re.sub(r'\[([^:\]]*):[^\]]*\]', r'\1', t)   # ZL alternatives use a colon; keep the first
    t = re.sub(r'@(\d+);', r'@\1', t)   # rare glyphs keep their own identity
    t = re.sub(r"\{[^}]*\}", '?', t)
    return [w for w in re.split(r'[.,\s]+', t) if w]

def load():
    lines, meta, cur = [], {}, None
    for raw in open(ZL, errors='ignore'):
        m = re.match(r'<(f\w+?)>\s+<!(.*)>', raw)
        if m:
            cur = m.group(1); meta[cur] = dict(re.findall(r'\$(\w)=(\w+)', m.group(2))); continue
        m = re.match(r'<(f\w+?)\.(\d+),([^>]*)>\s*(.*)', raw)
        if m:
            ws = clean(m.group(4))
            if ws: lines.append((m.group(1), int(m.group(2)), m.group(3), ws))
    return lines, meta

class KN:
    """Count-subtractable interpolated KN trigram. remove(folio) = leave-one-out."""
    D = 0.75
    def __init__(s, lines):
        s.by = collections.defaultdict(list)
        for f, n, loc, ws in lines: s.by[f].append(ws)
        s.c1 = collections.Counter()
        s.f2 = collections.defaultdict(collections.Counter)   # b -> c
        s.f3 = collections.defaultdict(collections.Counter)   # (a,b) -> c
        s.where = collections.defaultdict(collections.Counter)
        for f, L in s.by.items():
            for ws in L: s._add(f, ws, 1)
        s.freeze()
    def _add(s, f, ws, d):
        p = [BOS, BOS] + ws + [EOS]
        for i in range(2, len(p)):
            a, b, c = p[i-2], p[i-1], p[i]
            s.c1[c] += d; s.f2[b][c] += d; s.f3[(a, b)][c] += d; s.where[c][f] += d
    def remove(s, f):
        for ws in s.by[f]: s._add(f, ws, -1)
        s.freeze()
    def restore(s, f):
        for ws in s.by[f]: s._add(f, ws, 1)
        s.freeze()
    def freeze(s):
        s.N = sum(v for v in s.c1.values() if v > 0)
        s.n1 = sum(1 for v in s.c1.values() if v == 1)
        s.t2, s.t3 = {}, {}
    def _tot(s, cache, row, key):
        if key not in cache:
            vals = [v for v in row.values() if v > 0]; cache[key] = (sum(vals), len(vals))
        return cache[key]
    def prob(s, a, b, c, ch):
        new = s.n1 / s.N                                     # Good-Turing mass for unseen words
        p1 = (1 - new) * max(s.c1[c], 0) / s.N + new * ch.p(c)
        tot, typ = s._tot(s.t2, s.f2.get(b, {}), b)
        p2 = (max(s.f2[b][c] - s.D, 0) + s.D * typ * p1) / tot if tot else p1
        tot, typ = s._tot(s.t3, s.f3.get((a, b), {}), (a, b))
        return (max(s.f3[(a, b)][c] - s.D, 0) + s.D * typ * p2) / tot if tot else p2
    def index2(s): pass
    @property
    def _b2(s): return s.f2
    @property
    def follow2(s): return s.f3
    def vocab(s): return [w for w, v in s.c1.items() if v > 0]

class Char:
    """Char trigram spelling model; prices a word the word model has not seen."""
    def __init__(s, words):
        s.c = collections.Counter(); s.h = collections.Counter(); s.A = set('^$')
        for w in words:
            p = '^^' + w + '$'
            for i in range(2, len(p)): s.c[p[i-2:i+1]] += 1; s.h[p[i-2:i]] += 1; s.A.add(p[i])
    def p(s, w):
        p, lp = '^^' + w + '$', 0.0
        for i in range(2, len(p)): lp += math.log((s.c[p[i-2:i+1]] + 0.1) / (s.h[p[i-2:i]] + 0.1 * len(s.A)))
        return math.exp(lp)

LAM = 0.2   # weight on in-page context, the "earlier in this conversation" part

def ctx_prob(cache2, cache1, b, c):
    """Earlier-on-this-page model: what followed b so far, else what has appeared so far."""
    row = cache2.get(b)
    if row: return 0.7 * row[c] / sum(row.values()) + 0.3 * (cache1[c] / max(sum(cache1.values()), 1))
    return cache1[c] / max(sum(cache1.values()), 1)

def score_folio(m, ch, f, lam=LAM):
    """Book model (leave this folio out) mixed with an in-context cache of the page read so far."""
    m.remove(f); vocab = m.vocab(); out = []
    c2 = collections.defaultdict(collections.Counter); c1 = collections.Counter()
    for ws in m.by[f]:
        p = [BOS, BOS] + ws
        for i, w in enumerate(ws):
            a, b = p[i], p[i+1]
            P = lambda c: (1 - lam) * m.prob(a, b, c, ch) + lam * ctx_prob(c2, c1, b, c)
            pw = P(w); bits = -math.log2(max(pw, 1e-30))
            cand = {k for k, v in m.follow2.get((a, b), {}).items() if v > 0}
            cand |= {k for k, v in m._b2.get(b, {}).items() if v > 0} if len(cand) < 50 else set()
            cand |= set(c1)
            top = sorted(cand or vocab, key=lambda c: -P(c))[:5]
            out.append((w, bits, w in top[:1], w in top, ' '.join(ws[max(0, i-2):i])))
            c2[b][w] += 1; c1[w] += 1
    m.restore(f); return out

def weights():
    p = '../../../resources/readers/collection/voynich/token_prediction_2026-10-07/folio_weight.json'
    try: return {r['f']: r for r in json.load(open(p))}
    except Exception: return {}

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('cmd'); ap.add_argument('args', nargs='*')
    ap.add_argument('--n', type=int, default=15); ap.add_argument('--k', type=int, default=8); ap.add_argument('--json'); ap.add_argument('--lam', type=float, default=LAM)
    a = ap.parse_args(); lines, meta = load(); m = KN(lines)
    ch = Char([w for *_, ws in lines for w in ws])
    if a.cmd == 'rank':
        W = weights(); rows = []
        for f in m.by:
            r0 = score_folio(m, ch, f, 0.0); r = score_folio(m, ch, f, a.lam)
            if not r: continue
            n = len(r); b0 = sum(x[1] for x in r0) / n; b = sum(x[1] for x in r) / n
            rows.append(dict(folio=f, lang=meta.get(f, {}).get('L', ''), ill=meta.get(f, {}).get('I', ''), words=n,
                book_bits=round(b0, 2), bits=round(b, 2), ctx_gain=round(b0 - b, 2),
                top1=round(sum(x[2] for x in r) / n, 3), top5=round(sum(x[3] for x in r) / n, 3),
                unseen=round(sum(1 for w, *_ in r if not any(g != f for g in m.where[w] if m.where[w][g] > 0)) / n, 3),
                weight=W.get(f, {}).get('score')))
        rows.sort(key=lambda r: -r['ctx_gain'])
        if a.json: json.dump(rows, open(a.json, 'w'), indent=1)
        print(f"{'folio':8}{'L':>2}{'I':>2}{'words':>6}{'book':>7}{'+ctx':>7}{'gain':>6}{'top1':>6}{'top5':>6}{'unseen':>7}{'weight':>8}")
        for r in rows: print(f"{r['folio']:8}{r['lang']:>2}{r['ill']:>2}{r['words']:>6}{r['book_bits']:>7}{r['bits']:>7}{r['ctx_gain']:>6}{r['top1']:>6}{r['top5']:>6}{r['unseen']:>7}{str(r['weight'] if r['weight'] is not None else ''):>8}")
    elif a.cmd == 'folio':
        r = score_folio(m, ch, a.args[0], a.lam); n = len(r)
        print(f"{a.args[0]}: {n} words, {sum(x[1] for x in r)/n:.2f} bits/word, top1 {sum(x[2] for x in r)/n:.3f}, top5 {sum(x[3] for x in r)/n:.3f}")
        print('most surprising (bits, word, preceding context, seen elsewhere in book):')
        for w, bits, _, _, ctx in sorted(r, key=lambda x: -x[1])[:a.n]:
            print(f"  {bits:6.1f}  {w:16} after [{ctx}]  elsewhere x{sum(v for g, v in m.where[w].items() if g != a.args[0])}")
    elif a.cmd == 'next':
        fl, pos = a.args[0], int(a.args[1]); f, ln = fl.split('.')
        ws = next(x[3] for x in lines if x[0] == f and x[1] == int(ln))
        m.remove(f); m.index2(); p = [BOS, BOS] + ws; ctx = (p[pos], p[pos+1])
        cand = [k for k, v in m.follow2.get(ctx, {}).items() if v > 0] or [k for k, v in m._b2.get(ctx[1], {}).items() if v > 0] or m.vocab()
        tot = sorted(((m.prob(*ctx, c, ch), c) for c in cand), reverse=True)[:a.k]
        print(f"{fl} word {pos}: context [{' '.join(ctx)}]  actual = {ws[pos] if pos < len(ws) else EOS}")
        for pr, c in tot:
            src = ', '.join(g for g, _ in m.where[c].most_common(4))
            print(f"  {pr:6.3f}  {c:16} learned from {src}")
        m.restore(f)
if __name__ == '__main__': main()
