// engine.mjs: parse an IVTFF transliteration of the Voynich manuscript and measure it.
// Pure functions, no I/O: the same file runs in the browser and under node.

// ── parsing ──────────────────────────────────────────────────────────────────
// Returns pages: [{ folio, vars:{Q,P,F,B,I,L,H,C,X}, lines:[{ locus, type, words, paraStart, paraEnd }] }]
// opts.comma: 'space' (default: an uncertain word space counts as a space) or 'join'.
export function parseIVTFF(text, opts = {}) {
  const comma = opts.comma || 'space';
  const pages = []; let page = null;
  for (const raw of text.split(/\r?\n/)) {
    if (!raw || raw[0] === '#') continue;
    const m = raw.match(/^<([^>]+)>\s*(.*)$/);
    if (!m) continue;
    const id = m[1], body = m[2];
    if (!id.includes('.')) {                       // page header
      const vars = {};
      for (const v of body.matchAll(/\$([A-Z])=(\w+)/g)) vars[v[1]] = v[2];
      page = { folio: id, vars, lines: [] }; pages.push(page); continue;
    }
    if (!page) continue;
    const lm = id.match(/^([^.]+)\.([^,]+),(.)(\w\w?)$/);
    if (!lm) continue;
    const type = lm[4];
    let t = body;
    const paraStart = t.includes('<%>'), paraEnd = t.includes('<$>');
    t = t.replace(/<[-~]>/g, '.').replace(/<[^>]*>/g, '');
    t = t.replace(/\[([^\]]*)\]/g, (_, o) => o.split(':')[0]);
    t = t.replace(/[{}]/g, '');
    if (comma === 'join') t = t.replace(/,/g, ''); else t = t.replace(/,/g, '.');
    const words = t.split('.').filter(w => w.length);
    page.lines.push({ locus: lm[2], type, words, paraStart, paraEnd });
  }
  return pages;
}

export const isClean = w => /^[a-z]+$/.test(w);

// Running paragraph text only (locus type P*), as lines of words.
export function paragraphLines(pages, filter = () => true) {
  const out = [];
  for (const p of pages) {
    if (!filter(p)) continue;
    for (const l of p.lines) if (l.type[0] === 'P') out.push({ folio: p.folio, vars: p.vars, ...l });
  }
  return out;
}

// ── glyph segmentation ───────────────────────────────────────────────────────
// 'eva'   : every EVA letter is a symbol, as the file is written.
// 'bench' : the benched glyphs a reader sees as one shape are one symbol:
//           cth ckh cph cfh (bench gallows), ch sh (benches).
// 'bench+i': also the i-runs with their final stroke, as Currier's alphabet did:
//           iiin iin in iiir iir ir, and ee is left as two.
const BENCH = ['cth', 'ckh', 'cph', 'cfh', 'ch', 'sh'];
const IRUN = ['iiin', 'iin', 'in', 'iiir', 'iir', 'ir'];
export const SEGMENTATIONS = {
  eva: [],
  bench: BENCH,
  'bench+i': [...BENCH, ...IRUN],
};
export function segment(word, scheme = 'eva') {
  const units = SEGMENTATIONS[scheme];
  if (!units.length) return [...word];
  const out = [];
  for (let i = 0; i < word.length;) {
    let hit = null;
    for (const u of units) if (word.startsWith(u, i)) { hit = u; break; }
    if (hit) { out.push(hit); i += hit.length; } else { out.push(word[i]); i++; }
  }
  return out;
}

// ── character entropy ────────────────────────────────────────────────────────
// The text is a stream of symbols with one word-space symbol ' ' between words
// (and between lines). h1 = unigram entropy; h2 = H(next | previous), bits.
export function symbolStream(wordsSeq, seg = w => [...w]) {
  const s = [];
  for (const w of wordsSeq) { if (s.length) s.push(' '); for (const g of seg(w)) s.push(g); }
  return s;
}
export function entropies(stream) {
  const uni = new Map(), bi = new Map(), prev = new Map();
  for (let i = 0; i < stream.length; i++) {
    uni.set(stream[i], (uni.get(stream[i]) || 0) + 1);
    if (i) {
      const k = stream[i - 1] + '\u0001' + stream[i];
      bi.set(k, (bi.get(k) || 0) + 1);
      prev.set(stream[i - 1], (prev.get(stream[i - 1]) || 0) + 1);
    }
  }
  const N = stream.length;
  let h1 = 0; for (const c of uni.values()) h1 -= (c / N) * Math.log2(c / N);
  const M = N - 1; let hj = 0; for (const c of bi.values()) hj -= (c / M) * Math.log2(c / M);
  let hp = 0; for (const c of prev.values()) hp -= (c / M) * Math.log2(c / M);
  return { n: N, symbols: uni.size, h0: Math.log2(uni.size), h1, h2: hj - hp };
}

// ── line position ─────────────────────────────────────────────────────────────
// For each text given as lines of words: what share of all words ending in `glyph`
// stand last on their line, against the share of all words that are line-final.
export function lineFinalShare(lines, endsWith) {
  let words = 0, finals = 0, hit = 0, hitFinal = 0;
  for (const l of lines) {
    const w = l.words; if (!w.length) continue;
    for (let i = 0; i < w.length; i++) {
      words++; const last = i === w.length - 1; if (last) finals++;
      if (endsWith(w[i])) { hit++; if (last) hitFinal++; }
    }
  }
  return { words, finals, hit, hitFinal, baseRate: finals / words, share: hit ? hitFinal / hit : NaN };
}

// A deterministic PRNG (mulberry32), so every shuffle is reproducible.
export function rng(seed) {
  let a = seed >>> 0;
  return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
export function shuffle(arr, r) { const a = arr.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }

// ── any other text ───────────────────────────────────────────────────────────
// A line of ordinary text → words, each word an array of graphemes (a letter with its
// combining marks, so a scribe's q̃ is one symbol and q another). Lowercased; anything
// that is not a letter, a combining mark, or a scribal abbreviation sign is a word break.
const ABBREV = '⁊ꝑꝓꝕꝗꝙꝝꝫꝭꝯꝰ⸜⸝ꟾ';
const WORDCH = new RegExp(`[\\p{L}\\p{M}${ABBREV}]+`, 'gu');
export function graphemes(word) { return word.match(/\P{M}\p{M}*/gu) || []; }
export function wordsOfLine(line) {
  return (line.normalize('NFC').toLowerCase().match(WORDCH) || []).map(graphemes).filter(g => g.length);
}
// h2 measured in equal chunks, so texts of different lengths are compared fairly.
export function chunkedEntropy(stream, size = 20000) {
  const hs = [];
  for (let i = 0; i + size <= stream.length; i += size) hs.push(entropies(stream.slice(i, i + size)));
  if (!hs.length) return null;
  const med = k => { const v = hs.map(h => h[k]).sort((a, b) => a - b); return v[Math.floor(v.length / 2)]; };
  return { chunks: hs.length, size, h1: med('h1'), h2: med('h2'), h2min: Math.min(...hs.map(h => h.h2)), h2max: Math.max(...hs.map(h => h.h2)) };
}
// Line position as information: how many bits the last (or first) symbol of a word
// tells you about whether the word ends (or starts) a line, as a fraction of the
// uncertainty there is. 0 = the line is invisible to the word; 1 = it is fully visible.
// lines: array of lines, each an array of words, each word an array of symbols.
export function linePositionInfo(lines, which = 'last', minCount = 1, pool = 20) {
  const joint = new Map(); let N = 0, F = 0;
  for (const l of lines) {
    if (l.length < 2) continue;                   // a one-word line has no inside to compare with
    l.forEach((w, i) => {
      const g = which === 'last' ? w[w.length - 1] : w[0];
      const edge = which === 'last' ? i === l.length - 1 : i === 0;
      const k = g + (edge ? '\u0001' : '\u0002');
      joint.set(k, (joint.get(k) || 0) + 1); N++; if (edge) F++;
    });
  }
  const H = p => (p <= 0 || p >= 1) ? 0 : -(p * Math.log2(p) + (1 - p) * Math.log2(1 - p));
  const glyphs = new Map();
  for (const [k, c] of joint) { const g = k.slice(0, -1); const e = k.endsWith('\u0001'); const o = glyphs.get(g) || { n: 0, edge: 0 }; o.n += c; if (e) o.edge += c; glyphs.set(g, o); }
  // Rare symbols (fewer than `pool` words) are pooled into one class before the information is
  // measured, so a text with many rare signs is not flattered by the estimate's small-sample bias.
  const classes = new Map();
  for (const [g, o] of glyphs) { const c = o.n < pool ? '\u0000rare' : g; const q = classes.get(c) || { n: 0, edge: 0 }; q.n += o.n; q.edge += o.edge; classes.set(c, q); }
  let Hcond = 0;
  for (const o of classes.values()) Hcond += (o.n / N) * H(o.edge / o.n);
  const Hf = H(F / N);
  const top = [...glyphs].filter(([, o]) => o.n >= minCount).map(([g, o]) => ({ g, n: o.n, edge: o.edge, share: o.edge / o.n }))
    .sort((a, b) => b.share - a.share);
  return { words: N, edges: F, base: F / N, info: Hf ? (Hf - Hcond) / Hf : 0, top };
}

// ── neighbours ───────────────────────────────────────────────────────────────
export function editDistance(a, b) {          // a, b: arrays of symbols (or strings)
  const m = a.length, n = b.length; if (!m) return n; if (!n) return m;
  let prev = Array.from({ length: n + 1 }, (_, j) => j), cur = new Array(n + 1);
  for (let i = 1; i <= m; i++) { cur[0] = i; for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); [prev, cur] = [cur, prev]; }
  return prev[n];
}
// Share of adjacent word pairs (within a line) that are identical, or one edit apart,
// against the same share when the words of each block are shuffled (blocks: arrays of lines).
export function neighbourSimilarity(blocks, seed = 408, reps = 20) {
  const key = w => Array.isArray(w) ? w.join('\u0001') : w;
  const measure = bs => { let pairs = 0, same = 0, one = 0;
    for (const b of bs) for (const l of b) for (let i = 1; i < l.length; i++) { pairs++; const a = l[i - 1], c = l[i]; if (key(a) === key(c)) same++; else if (editDistance(a, c) === 1) one++; }
    return { pairs, same: same / pairs, one: one / pairs }; };
  const obs = measure(blocks); const r = rng(seed); let s = 0, o = 0;
  for (let t = 0; t < reps; t++) {
    const sh = blocks.map(b => { const ws = shuffle(b.flat(), r); let k = 0; return b.map(l => l.map(() => ws[k++])); });
    const m = measure(sh); s += m.same; o += m.one;
  }
  return { ...obs, nullSame: s / reps, nullOne: o / reps };
}

// ── pages as letter-pair profiles ────────────────────────────────────────────
export function pairProfile(pageWords, k = 60) {
  const cnt = pageWords.map(ws => { const m = new Map(); let n = 0; for (const w of ws) { const s = '^' + w + '$'; for (let i = 1; i < s.length; i++) { const b = s.slice(i - 1, i + 1); m.set(b, (m.get(b) || 0) + 1); n++; } } return { m, n }; });
  const tot = new Map(); for (const c of cnt) for (const [b, v] of c.m) tot.set(b, (tot.get(b) || 0) + v);
  const feats = [...tot].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, k).map(x => x[0]);
  let X = cnt.map(c => feats.map(f => (c.m.get(f) || 0) / c.n));
  const mu = feats.map((_, j) => X.reduce((s, r) => s + r[j], 0) / X.length);
  const sd = feats.map((_, j) => Math.sqrt(X.reduce((s, r) => s + (r[j] - mu[j]) ** 2, 0) / X.length) || 1);
  X = X.map(r => r.map((v, j) => (v - mu[j]) / sd[j]));
  return { X, feats };
}
export const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
export function kmeans(X, k, seed) {
  const r = rng(seed); let C = shuffle(X, r).slice(0, k).map(v => v.slice()); let lab = [];
  for (let it = 0; it < 100; it++) {
    const nl = X.map(x => { let b = 0, bd = Infinity; C.forEach((c, i) => { const d = x.reduce((s, v, j) => s + (v - c[j]) ** 2, 0); if (d < bd) { bd = d; b = i; } }); return b; });
    if (nl.join() === lab.join()) break; lab = nl;
    C = C.map((c, i) => { const m = X.filter((_, t) => lab[t] === i); return m.length ? c.map((_, j) => m.reduce((s, v) => s + v[j], 0) / m.length) : c; });
  }
  const sse = X.reduce((s, x, t) => s + x.reduce((a, v, j) => a + (v - C[lab[t]][j]) ** 2, 0), 0);
  return { lab, sse };
}
// Leading principal components by power iteration with deflation (X already centred).
export function principalComponents(X, n = 2) {
  const d = X[0].length; const cov = Array.from({ length: d }, () => new Array(d).fill(0));
  for (const x of X) for (let i = 0; i < d; i++) for (let j = 0; j < d; j++) cov[i][j] += x[i] * x[j] / X.length;
  const out = [];
  for (let c = 0; c < n; c++) {
    let v = Array.from({ length: d }, (_, i) => 1 / Math.sqrt(d) + i * 1e-6);
    for (let it = 0; it < 500; it++) { const w = cov.map(row => dot(row, v)); const nr = Math.sqrt(dot(w, w)); v = w.map(x => x / nr); }
    const lam = dot(v, cov.map(row => dot(row, v)));
    if (v.reduce((s, x) => s + x, 0) < 0) v = v.map(x => -x);          // fix the sign so the picture is reproducible
    out.push(v);
    for (let i = 0; i < d; i++) for (let j = 0; j < d; j++) cov[i][j] -= lam * v[i] * v[j];
  }
  return out;
}

// Identical words across a line break (last word of a line, first word of the next line of the
// same paragraph) against identical neighbours inside lines. Only clean words count.
export function repeatsAcrossLines(pages, filter = () => true) {
  let words = 0, inPairs = 0, inSame = 0, acPairs = 0, acSame = 0; const cases = [];
  for (const p of pages) {
    if (!filter(p)) continue;
    const ls = p.lines.filter(l => l.type[0] === 'P');
    for (let i = 0; i < ls.length; i++) {
      const w = ls[i].words; words += w.filter(isClean).length;
      for (let j = 1; j < w.length; j++) if (isClean(w[j - 1]) && isClean(w[j])) { inPairs++; if (w[j - 1] === w[j]) inSame++; }
      const nx = ls[i + 1];
      if (nx && !ls[i].paraEnd && !nx.paraStart && w.length && nx.words.length) {
        const a = w[w.length - 1], b = nx.words[0];
        if (isClean(a) && isClean(b)) { acPairs++; if (a === b) { acSame++; cases.push(`${p.folio}.${ls[i].locus}: ${a} / ${b}`); } }
      }
    }
  }
  return { words, inPairs, inSame, acPairs, acSame, expected: acPairs * inSame / inPairs, cases };
}

// ── the whole comparison, one function, shared by the page, the research scripts and the verifier ──
// L: lines → words → symbols. Neighbour blocks are runs of 30 lines, the same for every text.
export function measureLines(L, reps = 10) {
  const st = symbolStream(L.flat(), w => w);
  const ce = chunkedEntropy(st);
  const lf = linePositionInfo(L, 'last'), li = linePositionInfo(L, 'first');
  const blocks = []; for (let i = 0; i < L.length; i += 30) blocks.push(L.slice(i, i + 30));
  const nb = neighbourSimilarity(blocks, 408, reps);
  return { lines: L.length, words: L.reduce((s, l) => s + l.length, 0),
    h1: ce && ce.h1, h2: ce && ce.h2, h2min: ce && ce.h2min, h2max: ce && ce.h2max, h2chunks: ce && ce.chunks,
    lastInfo: lf.info, firstInfo: li.info, base: lf.base,
    topLast: lf.top.filter(t => t.n >= 30).slice(0, 3).map(t => ({ g: t.g, share: t.share, n: t.n })),
    topFirst: li.top.filter(t => t.n >= 30).slice(0, 3).map(t => ({ g: t.g, share: t.share, n: t.n })),
    pairs: nb.pairs, same: nb.same, nullSame: nb.nullSame, one: nb.one, nullOne: nb.nullOne };
}
// Every Voynich number the page prints, from the transliteration's text.
export function measureVoynich(text) {
  const pages = parseIVTFF(text);
  const pl = paragraphLines(pages);
  const all = pl.flatMap(l => l.words), clean = all.filter(isClean);
  const VL = pl.map(l => l.words.filter(isClean)).filter(l => l.length);
  const segs = {};
  for (const s of Object.keys(SEGMENTATIONS)) segs[s] = measureLines(VL.map(l => l.map(w => segment(w, s))));
  const chars = VL.map(l => l.map(w => [...w]));
  const inner = pl.filter(l => !l.paraStart && !l.paraEnd).map(l => l.words.filter(isClean).map(w => [...w])).filter(l => l.length);
  const tbl = (L, which) => linePositionInfo(L, which).top.filter(t => t.n >= 50).map(t => ({ g: t.g, n: t.n, edge: t.edge }));
  const pageBlocks = pages.map(p => p.lines.filter(l => l.type[0] === 'P').map(l => l.words.filter(isClean).map(w => [...w])).filter(l => l.length)).filter(b => b.length);
  const nbPage = neighbourSimilarity(pageBlocks, 408, 10);
  // the page map
  const pp = pages.map(p => ({ folio: p.folio, L: p.vars.L || null, H: p.vars.H || null, I: p.vars.I || null, Q: p.vars.Q || null,
    ws: p.lines.filter(l => l.type[0] === 'P').flatMap(l => l.words).filter(isClean) })).filter(p => p.ws.length >= 60);
  const { X, feats } = pairProfile(pp.map(p => p.ws), 60);
  let best = null; for (let s = 1; s <= 50; s++) { const r = kmeans(X, 2, s); if (!best || r.sse < best.sse) best = r; }
  const [pc1, pc2] = principalComponents(X, 2);
  const aOf = c => pp.filter((p, i) => best.lab[i] === c && p.L === 'A').length;
  const aC = aOf(0) >= aOf(1) ? 0 : 1;
  const map = pp.map((p, i) => ({ folio: p.folio, L: p.L, H: p.H, I: p.I, Q: p.Q, words: p.ws.length, x: dot(X[i], pc1), y: dot(X[i], pc2), cluster: best.lab[i] === aC ? 'A' : 'B' }));
  const labelled = map.filter(p => p.L === 'A' || p.L === 'B');
  // Can the same profile name Davis's scribe? Leave-one-out nearest centroid, scored against
  // always guessing the commonest scribe, on all pages and on herbal pages in language B alone.
  const loo = idx => { let hit = 0;
    for (const i of idx) { const c = {};
      for (const j of idx) if (j !== i) { const l = pp[j].H; (c[l] ||= { s: feats.map(() => 0), n: 0 }); c[l].n++; X[j].forEach((v, t) => c[l].s[t] += v); }
      let b = null, bd = Infinity; for (const [l, q] of Object.entries(c)) { const d = X[i].reduce((s, v, t) => s + (v - q.s[t] / q.n) ** 2, 0); if (d < bd) { bd = d; b = l; } }
      if (b === pp[i].H) hit++; }
    const cnt = {}; for (const i of idx) cnt[pp[i].H] = (cnt[pp[i].H] || 0) + 1;
    return { n: idx.length, hit, majority: Math.max(...Object.values(cnt)), counts: cnt }; };
  const idx = pp.map((_, i) => i).filter(i => pp[i].H);
  const scribes = { all: loo(idx), herbalB: loo(idx.filter(i => pp[i].I === 'H' && pp[i].L === 'B')) };
  return { scribes,
    counts: { pages: pages.length, paragraphLines: pl.length, words: all.length, cleanWords: clean.length, types: new Set(clean).size,
      paraStart: pl.filter(l => l.paraStart).length, paraEnd: pl.filter(l => l.paraEnd).length, innerLines: inner.length },
    segs, base: linePositionInfo(chars, 'last').base,
    inner: { lastInfo: linePositionInfo(inner, 'last').info, firstInfo: linePositionInfo(inner, 'first').info },
    lastGlyphs: tbl(chars, 'last'), firstGlyphs: tbl(chars, 'first'),
    neighboursByPage: { pairs: nbPage.pairs, same: nbPage.same, nullSame: nbPage.nullSame, one: nbPage.one, nullOne: nbPage.nullOne },
    across: { herbalBio: repeatsAcrossLines(pages, p => p.vars.I === 'H' || p.vars.I === 'B'), rest: repeatsAcrossLines(pages, p => !(p.vars.I === 'H' || p.vars.I === 'B')) },
    map, features: feats, agree: labelled.filter(p => p.cluster === p.L).length, labelled: labelled.length,
  };
}
