// engine.mjs: the Kolakoski sequence and its walk, for /strata/its-own-description/.
// Runs unchanged in the reader's browser and in the verifier (Node 18+). No dependencies.
//
// The Kolakoski sequence K (OEIS A000002) is the one sequence of 1s and 2s, starting with 1,
// whose run lengths are the sequence itself: 1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,...
// delta(n) = (number of 2s) - (number of 1s) among the first n terms.

// The direct way: a write head runs ahead of a read head on one tape. The term under the read
// head says how long the next run is; the symbol of the runs alternates 1, 2, 1, 2, ...
// Linear time and linear memory. Returns a Uint8Array of the first n terms.
export function prefix(n) {
  const a = new Uint8Array(Math.max(n, 3));
  a[0] = 1; a[1] = 2; a[2] = 2;
  let w = 3, r = 2, sym = 1;
  while (w < n) {
    const len = a[r++];
    a[w++] = sym;
    if (len === 2 && w < n) a[w++] = sym;
    sym = 3 - sym;
  }
  return a.subarray(0, n);
}

// The machine as the page animates it: each step reads one term and writes one run.
// Returns the list of steps for the first `steps` reads: { read: index read, len, sym, wrote: [indices] }.
export function machineSteps(steps) {
  const a = [1, 2, 2];
  const out = [{ read: 0, len: 1, sym: 1, wrote: [0] }, { read: 1, len: 2, sym: 2, wrote: [1, 2] }];
  let r = 2, sym = 1;
  while (out.length < steps) {
    const len = a[r];
    const wrote = [];
    for (let i = 0; i < len; i++) { wrote.push(a.length); a.push(sym); }
    out.push({ read: r, len, sym, wrote });
    r++; sym = 3 - sym;
  }
  return { steps: out.slice(0, steps), terms: a };
}

// Nilsson's log-space generator (J. Integer Sequences 15 (2012), Art. 12.6.7, Algorithm 2).
// Each level k holds the run it is emitting: its symbol and how many of it remain (1 or 2).
// next() returns K_3, K_4, K_5, ...  Memory grows like log n; time is linear.
export function nilsson() {
  const sym = new Uint8Array(128), rem = new Uint8Array(128);
  let top = 0;
  function inc(k) {
    if (k === top) { sym[k] = 2; rem[k] = 2; top++; }
    if (rem[k] === 2) { rem[k] = 1; return sym[k]; }
    sym[k] = 3 - sym[k];
    rem[k] = inc(k + 1);
    return sym[k];
  }
  return { next: () => inc(0), depth: () => top };
}

// Walk the first n terms. Calls sample(m, delta) at every m in `at` (sorted ascending),
// and returns totals: ones, delta, maxAbs (max |delta(m)| for m <= n), zeros (#m <= n with delta(m) = 0),
// runs (number of runs that have started by n).
export function walk(n, at = [], sample = () => {}) {
  const g = nilsson();
  let m = 0, ones = 0, delta = 0, maxAbs = 0, zeros = 0, runs = 0, prev = 0, ai = 0;
  const step = (s) => {
    m++;
    if (s === 1) { ones++; delta--; } else delta++;
    if (s !== prev) { runs++; prev = s; }
    if (delta === 0) zeros++;
    const q = delta < 0 ? -delta : delta;
    if (q > maxAbs) maxAbs = q;
    while (ai < at.length && at[ai] === m) { sample(m, delta, runs, ones); ai++; }
  };
  if (n >= 1) step(1);
  if (n >= 2) step(2);
  while (m < n) step(g.next());
  return { n: m, ones, delta, maxAbs, zeros, runs, depth: g.depth() };
}

// A small seeded generator (mulberry32), so a page draw can be named and repeated.
export function rng(seed) {
  let t = seed >>> 0;
  return () => {
    t = (t + 0x6D2B79F5) >>> 0;
    let x = Math.imul(t ^ (t >>> 15), 1 | t);
    x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
  };
}

// Read a sequence of 1s and 2s as run lengths: 1^{s1} 2^{s2} 1^{s3} ... (Brent's map T1).
export function decode(s, limit = Infinity) {
  let len = 0;
  for (let i = 0; i < s.length; i++) len += s[i];
  len = Math.min(len, limit);
  const out = new Uint8Array(len);
  let w = 0, sym = 1;
  for (let i = 0; i < s.length && w < len; i++) {
    for (let r = 0; r < s[i] && w < len; r++) out[w++] = sym;
    sym = 3 - sym;
  }
  return out;
}

// The tower: start from fair coin flips and read the result as run lengths `levels` times.
// Level 0 is the coins themselves; level 1 obeys the same local rule as K (runs of 1 or 2, symbols
// alternating) but its run lengths are coin flips. Returns the first n terms of the top level.
export function tower(levels, n, seed) {
  const R = rng(seed);
  let len = Math.min(n, Math.ceil(n / Math.pow(1.5, levels) * 1.2) + 64);
  let s = new Uint8Array(len);
  for (let i = 0; i < len; i++) s[i] = R() < 0.5 ? 1 : 2;
  for (let k = 0; k < levels; k++) s = decode(s, n);
  return s.subarray(0, n);
}

// delta statistics of any 1/2 array: final delta, max |delta|, zeros, and a downsampled trace.
export function stats(s, points = 0) {
  let d = 0, mx = 0, zeros = 0;
  const trace = points ? new Float64Array(points) : null;
  const every = points ? s.length / points : 0;
  let next = every, k = 0;
  for (let i = 0; i < s.length; i++) {
    d += s[i] === 2 ? 1 : -1;
    if (d === 0) zeros++;
    const q = d < 0 ? -d : d;
    if (q > mx) mx = q;
    if (points && i + 1 >= next && k < points) { trace[k++] = d; next += every; }
  }
  return { n: s.length, delta: d, maxAbs: mx, zeros, trace };
}

// The cancellation identity. Let K_1..K_m be read as run lengths (as in decode). At the end of the
// m-th run written, (2s - 1s) equals the alternating sum  sum_{i<=m} (-1)^i K_i. A run of two equal
// terms at positions j, j+1 contributes K_j - K_j = 0 to that sum, so only terms standing alone
// (runs of length 1) survive. Returns { alt, survivors } for the first m terms of s.
export function alternating(s, m) {
  let alt = 0;
  const survivors = [];
  for (let i = 0; i < m; i++) alt += (i % 2 === 0 ? -1 : 1) * s[i];   // i is 0-based, so (-1)^(i+1)
  for (let i = 0; i < m; i++) {
    const alone = (i === 0 || s[i - 1] !== s[i]) && (i + 1 >= s.length || s[i + 1] !== s[i]);
    if (alone) survivors.push(i);
  }
  return { alt, survivors };
}

// ---------- the tower, calculated instead of sampled ----------
// One reading (decode) is a machine with one digit of memory: the digit it writes next. It reads a
// term x, writes x copies of that digit, and switches digit. Stack j readings and you have one machine
// with 2^j memory states that eats one coin flip and writes a block of terms at the top level.
// State s: bit k-1 is (next digit of reading k) - 1, so reading 1 (the one that eats coins) is bit 0.
// Entry 2s + (coin - 1) of the returned arrays: next state, (2s - 1s) written at the top, terms written.
export function readingMachine(j) {
  // the top level (no readings above it): one term in, one term out
  let next = Int32Array.from([0, 0]), R = Int32Array.from([-1, 1]), L = Int32Array.from([1, 1]);
  for (let k = j; k >= 1; k--) {          // add reading k beneath the stack k+1..j
    const m = next.length / 2, n = 2 * m;
    const nN = new Int32Array(2 * n), nR = new Int32Array(2 * n), nL = new Int32Array(2 * n);
    for (let rest = 0; rest < m; rest++) {
      for (let d = 0; d <= 1; d++) {        // the digit reading k writes next, minus 1
        const s = d + 2 * rest;
        for (let x = 1; x <= 2; x++) {      // the term reading k reads
          let r = 0, l = 0, cur = rest;
          for (let c = 0; c < x; c++) { const e = 2 * cur + d; r += R[e]; l += L[e]; cur = next[e]; }
          const e = 2 * s + x - 1;
          nR[e] = r; nL[e] = l; nN[e] = (1 - d) + 2 * cur;   // the digit switches once per term read
        }
      }
    }
    next = nN; R = nR; L = nL;
  }
  return { j, n: next.length / 2, next, R, L };
}

// The long-run spread of the walk at level j, per term: lim (2s - 1s)^2 / n. Every state of the machine
// has exactly two ways in, so in the long run each is equally likely, and the average of R is zero.
// The potential h solves h(s) - (h(next(s,1)) + h(next(s,2)))/2 = (R(s,1) + R(s,2))/2; then the push
// of a coin, R + h(next) - h(s), is how far that coin moves the walk's long-run expected position, the
// pushes are uncorrelated, and the spread per coin is their mean square. Per term: divide by the mean
// block length, (3/2)^j. Iterates the half-lazy chain until the remainder is below tol.
export function towerSpread(j, tol = 1e-13) {
  if (j === 0) return { j, perTerm: 1, perCoin: 1, block: 1, push: Float64Array.of(1, -1), iterations: 0 };
  const { n, next, R, L } = readingMachine(j);
  let g = new Float64Array(n), h = new Float64Array(n), t = new Float64Array(n), it = 0;
  for (let s = 0; s < n; s++) g[s] = (R[2 * s] + R[2 * s + 1]) / 2;
  for (; it < 1e6; it++) {
    let mean = 0, max = 0;
    for (let s = 0; s < n; s++) { h[s] += g[s] / 2; t[s] = (g[s] + (g[next[2 * s]] + g[next[2 * s + 1]]) / 2) / 2; mean += t[s]; }
    mean /= n;
    for (let s = 0; s < n; s++) { t[s] -= mean; const q = Math.abs(t[s]); if (q > max) max = q; }
    [g, t] = [t, g];
    if (max < tol) break;
  }
  const push = new Float64Array(2 * n);
  let sq = 0, len = 0;
  for (let e = 0; e < 2 * n; e++) { push[e] = R[e] + h[next[e]] - h[e >> 1]; sq += push[e] * push[e]; len += L[e]; }
  const perCoin = sq / (2 * n), block = len / (2 * n);
  return { j, perTerm: perCoin / block, perCoin, block, push, iterations: it };
}

// The same, exactly, in fractions (BigInt), by Gaussian elimination: small j only (64 states at j = 6).
// Returns { perTerm, perCoin, block, push } as [numerator, denominator] pairs of BigInt in lowest terms
// (push: one per entry 2s + coin - 1, as in towerSpread).
export function towerExact(j) {
  const gcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) [a, b] = [b, a % b]; return a; };
  const fr = (p, q = 1n) => { if (q < 0n) { p = -p; q = -q; } const d = gcd(p, q) || 1n; return [p / d, q / d]; };
  const add = (a, b) => fr(a[0] * b[1] + b[0] * a[1], a[1] * b[1]);
  const sub = (a, b) => fr(a[0] * b[1] - b[0] * a[1], a[1] * b[1]);
  const mul = (a, b) => fr(a[0] * b[0], a[1] * b[1]);
  const div = (a, b) => fr(a[0] * b[1], a[1] * b[0]);
  if (j === 0) return { j, perTerm: [1n, 1n], perCoin: [1n, 1n], block: [1n, 1n], push: [[1n, 1n], [-1n, 1n]] };
  const { n, next, R, L } = readingMachine(j);
  // rows: h(s) - h(next1)/2 - h(next2)/2 = (R1 + R2)/2, the last replaced by sum h = 0 (h is up to a constant)
  const A = Array.from({ length: n }, () => Array.from({ length: n + 1 }, () => [0n, 1n]));
  for (let s = 0; s < n - 1; s++) {
    A[s][s] = add(A[s][s], [1n, 1n]);
    for (let c = 0; c < 2; c++) A[s][next[2 * s + c]] = sub(A[s][next[2 * s + c]], [1n, 2n]);
    A[s][n] = fr(BigInt(R[2 * s] + R[2 * s + 1]), 2n);
  }
  for (let s = 0; s < n; s++) A[n - 1][s] = [1n, 1n];
  for (let c = 0; c < n; c++) {
    let p = c; while (A[p][c][0] === 0n) p++;
    [A[c], A[p]] = [A[p], A[c]];
    for (let r = 0; r < n; r++) {
      if (r === c || A[r][c][0] === 0n) continue;
      const f = div(A[r][c], A[c][c]);
      for (let k = c; k <= n; k++) if (A[c][k][0] !== 0n) A[r][k] = sub(A[r][k], mul(f, A[c][k]));
    }
  }
  const h = A.map((row, s) => div(row[n], row[s]));
  let sq = [0n, 1n], len = 0n;
  const push = [];
  for (let e = 0; e < 2 * n; e++) {
    const p = add(sub(h[next[e]], h[e >> 1]), [BigInt(R[e]), 1n]);
    push.push(p); sq = add(sq, mul(p, p)); len += BigInt(L[e]);
  }
  const perCoin = div(sq, [BigInt(2 * n), 1n]), block = fr(len, BigInt(2 * n));
  return { j, perTerm: div(perCoin, block), perCoin, block, push };
}
