// machines.mjs: the texts known to mean nothing, and the short-scale windows, as pure functions.
// The same file runs in the browser and under node (research/voynich-machines/). Every
// measurement itself is the Voynich layer's engine.mjs, imported unmodified.
import * as E from '../is-the-voynich-manuscript-a-language/engine.mjs';
export { E };

// The manuscript's clean paragraph words, one entry per line, exactly as measureVoynich() takes them.
export function voynichLines(ivtff) {
  return E.paragraphLines(E.parseIVTFF(ivtff)).map(l => l.words.filter(E.isClean)).filter(l => l.length);
}

// Timm and Schinner's generator output: '#' property lines, then one line of text per line,
// words separated by spaces. Only clean EVA words count, as for the manuscript.
export function selfCitationLines(text) {
  return text.split(/\r?\n/).filter(l => l && l[0] !== '#')
    .map(l => l.trim().split(/\s+/).filter(E.isClean)).filter(l => l.length);
}

// A word-bigram chain trained on the manuscript. Transitions are counted over the running text
// (across line breaks), so the chain knows which word follows which and nothing about where a
// line ends. Output line k gets the word count of manuscript line k.
export function markovLines(VL, seed) {
  const flat = VL.flat(), next = new Map();
  for (let i = 1; i < flat.length; i++) { const a = flat[i - 1]; if (!next.has(a)) next.set(a, []); next.get(a).push(flat[i]); }
  const r = E.rng(seed);
  let w = flat[Math.floor(r() * flat.length)];
  return VL.map(l => l.map(() => {
    const o = next.get(w);
    w = o ? o[Math.floor(r() * o.length)] : flat[Math.floor(r() * flat.length)];
    return w;
  }));
}

// The manuscript's words, shuffled over the whole text; line lengths kept.
export function shuffledLines(VL, seed) {
  const ws = E.shuffle(VL.flat(), E.rng(seed)); let k = 0;
  return VL.map(l => l.map(() => ws[k++]));
}

// A verbose cipher: base letters only; each letter, by its frequency rank in its book, becomes
// the manuscript's bench+i glyph unit of the same frequency rank.
export function baseLetters(line) {
  return line.normalize('NFD').toLowerCase().replace(/\p{M}/gu, '').split(/[^a-z]+/).filter(Boolean);
}
export function voynichUnitsByRank(VL) {
  const c = new Map();
  for (const w of VL.flat()) for (const u of E.segment(w, 'bench+i')) c.set(u, (c.get(u) || 0) + 1);
  return [...c].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(x => x[0]);
}
export function verboseCipher(latinLines, units) {
  const L = latinLines.map(baseLetters).filter(l => l.length);
  const c = new Map(); for (const w of L.flat()) for (const ch of w) c.set(ch, (c.get(ch) || 0) + 1);
  const rank = [...c].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(x => x[0]);
  if (rank.length > units.length) throw new Error('more letters than units');
  const key = new Map(rank.map((ch, i) => [ch, units[i]]));
  return { key: Object.fromEntries(key), lines: L.map(l => l.map(w => [...w].map(ch => key.get(ch)).join(''))) };
}

export const asEva = L => L.map(l => l.map(w => [...w]));

// The long scale: exactly what the fifty books were given, plus the two ratios.
export function measureLong(L) {
  const m = E.measureLines(L);
  return { lines: m.lines, words: m.words, h2: m.h2, h2chunks: m.h2chunks,
    same: m.same, nullSame: m.nullSame, sameRatio: m.same / m.nullSame,
    one: m.one, nullOne: m.nullOne, oneRatio: m.one / m.nullOne,
    lastInfo: m.lastInfo, firstInfo: m.firstInfo, topLast: m.topLast, topFirst: m.topFirst };
}

// ── the short scale ──────────────────────────────────────────────────────────
// Windows of consecutive whole lines reaching at least MIN words; a remainder under MIN is dropped.
// Line position pools symbols seen fewer than POOL times (not 20, as at the long scale), for every
// text alike. Neighbours are pooled over a text's windows, each window shuffled within itself.
export const MIN = 150, POOL = 5;
export function windows(L, min = MIN) {
  const out = []; let cur = [], n = 0;
  for (const l of L) { cur.push(l); n += l.length; if (n >= min) { out.push(cur); cur = []; n = 0; } }
  return out;
}
// At this size the line-position estimate is biased upward even for a text that knows nothing of
// its lines, so each window also carries its own floor: the same words shuffled across the window's
// lines (line lengths kept), measured the same way, averaged over REPS shuffles. (Added after the
// first run, when a line-blind machine scored 0.05 to 0.09 here; not in the pre-registration.)
export const REPS = 10;
export function measureWindow(W) {
  const st = E.symbolStream(W.flat(), w => w);
  const h = E.entropies(st);
  const info = (L, which) => E.linePositionInfo(L, which, 1, POOL).info;
  const r = E.rng(408); let nl = 0, nf = 0;
  for (let t = 0; t < REPS; t++) {
    const ws = E.shuffle(W.flat(), r); let k = 0; const S = W.map(l => l.map(() => ws[k++]));
    nl += info(S, 'last'); nf += info(S, 'first');
  }
  return { words: W.reduce((s, l) => s + l.length, 0), lines: W.length, symbols: st.length, h2: h.h2,
    lastInfo: info(W, 'last'), firstInfo: info(W, 'first'), lastFloor: nl / REPS, firstFloor: nf / REPS };
}
export function measureShort(L) {
  const ws = windows(L);
  if (!ws.length) return null;
  const nb = E.neighbourSimilarity(ws, 408, 20);
  return { windows: ws.map(measureWindow), pairs: nb.pairs, same: nb.same, nullSame: nb.nullSame, one: nb.one, nullOne: nb.nullOne };
}
