// verify-collatz.mjs: checks every claim /strata/collatz/ computes, against the engine
// the page actually runs (public/strata/collatz/collatz.mjs) and a second, deliberately
// naive implementation written here from scratch.
//
//   node verify-collatz.mjs
//
// Needs only Node 18+. Run inside the repository it tests the local engine; run from an
// empty directory it downloads the engine from https://artwaste.land/strata/collatz/
// collatz.mjs (the bytes your browser runs) and OEIS A076227's b-file from oeis.org.
// Exit 0 = every check passed.

import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const localEngine = join(here, 'public/strata/collatz/collatz.mjs');
let C, engineFrom;
if (existsSync(localEngine)) { C = await import(localEngine); engineFrom = localEngine; }
else {
  const url = 'https://artwaste.land/strata/collatz/collatz.mjs';
  const src = await (await fetch(url)).text();
  C = await import('data:text/javascript;base64,' + Buffer.from(src).toString('base64'));
  engineFrom = url;
}

let fails = 0, passes = 0;
const ok = (cond, msg) => { if (cond) passes++; else fails++; console.log((cond ? 'PASS  ' : 'FAIL  ') + msg); };
console.error(`engine: ${engineFrom}`);   // stderr: where the engine came from is not part of the result

// ── the naive twin ──────────────────────────────────────────────────────────
// Plain Numbers where they are safe, written without looking at the engine.
function naiveSteps(n) { let s = 0, p = n; while (n !== 1) { n = n % 2 ? 3 * n + 1 : n / 2; if (n > p) p = n; s++; } return [s, p]; }

// ── 1. the machine ──────────────────────────────────────────────────────────
{
  let bad = 0;
  for (let n = 1; n < 100000; n++) {
    const h = C.hailstone(n); const [s, p] = naiveSteps(n);
    if (h.steps !== s || h.peak !== BigInt(p) || !h.reached || h.odd + h.even !== s) bad++;
  }
  ok(bad === 0, `engine hailstone() agrees with the naive twin on steps and peak for every start below 100,000 (${bad} disagreements)`);
  const h6 = C.hailstone(6), h7 = C.hailstone(7), h27 = C.hailstone(27);
  ok(h6.path.join(',') === '6,3,10,5,16,8,4,2,1', '6 goes 6, 3, 10, 5, 16, 8, 4, 2, 1');
  ok(h7.steps === 16 && h7.peak === 52n, `7 takes ${h7.steps} steps and peaks at ${h7.peak} (page: sixteen, 52)`);
  ok(h27.steps === 111 && h27.peak === 9232n, `27 takes ${h27.steps} steps and peaks at ${h27.peak} (page: 111, 9,232)`);
}
{
  // record holders, by a memoised naive count (independent of the engine)
  const LIM = 10000000; const memo = new Uint16Array(LIM); let best = 0, arg = 0, best1k = 0, arg1k = 0;
  for (let n = 2; n < LIM; n++) {
    let x = n, s = 0;
    while (x >= n) { x = x % 2 ? 3 * x + 1 : x / 2; s++; }   // run until it falls below n, whose count is known
    const t = s + (x === 1 ? 0 : memo[x]); memo[n] = t;
    if (t > best) { best = t; arg = n; }
    if (n < 1000 && t > best1k) { best1k = t; arg1k = n; }
  }
  ok(arg === 8400511 && best === 685, `slowest start below 10^7: ${arg.toLocaleString('en-US')} with ${best} steps (page: 8,400,511)`);
  ok(arg1k === 871 && best1k === 178, `slowest start below 1,000: ${arg1k} with ${best1k} steps (page offers 871 as a slow one)`);
  const e = C.hailstone(8400511); ok(e.steps === 685, `the engine agrees: 8,400,511 takes ${e.steps} steps`);
}
{
  // 2^100 - 1: a hundred odd shortcut steps in a row, then 3^100 - 1 (Lagarias 2010, sec. 3.2)
  const v = C.parityVector(2n ** 100n - 1n, 101);
  let x = 2n ** 100n - 1n; for (let i = 0; i < 100; i++) x = (3n * x + 1n) / 2n;
  ok(v.slice(0, 100).every((b) => b === 1) && v[100] === 0 && x === 3n ** 100n - 1n,
    '2^100 − 1 makes 100 odd shortcut steps in a row and arrives at 3^100 − 1, which is even');
}
{
  // the coin-flip model: log10(3/4)/3 per hailstone step, i.e. about 24 steps per decimal digit
  const slope = Math.log10(3 / 4) / 3;
  ok(Math.abs(Math.sqrt(0.75) - 0.866) < 5e-4 && Math.round(-1 / slope) === 24, `drift ×${Math.sqrt(0.75).toFixed(4)} per decision; one decimal digit per ${(-1 / slope).toFixed(2)} steps (page: 0.866, 24)`);
  // seeded random 100-digit starts, so this check prints the same thing every run
  let seed = 20260926; const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
  const steps = [];
  for (let t = 0; t < 400; t++) { let s = String(1 + Math.floor(rnd() * 9)); for (let i = 0; i < 99; i++) s += Math.floor(rnd() * 10); steps.push(C.hailstone(s).steps); }
  steps.sort((a, b) => a - b);
  const pred = Math.log10(1e99 * 5) / -slope; const med = steps[200];
  ok(Math.abs(med - pred) / pred < 0.05, `400 seeded random 100-digit starts: median ${med} steps, model ${pred.toFixed(0)} (range ${steps[0]} to ${steps[399]}); page says "about 2,400" and "land around it"`);
}

// ── 2. the last k bits decide the first k moves ─────────────────────────────
function naiveParity(n, k) { let w = 0; for (let i = 0; i < k; i++) { if (n % 2) { w |= 1 << i; n = (3 * n + 1) / 2; } else n = n / 2; } return w >>> 0; }
{
  let allBij = true, agree = true;
  for (let k = 1; k <= 20; k++) {
    const N = 2 ** k, seen = new Uint8Array(N);
    for (let r = 0; r < N; r++) seen[naiveParity(r + N, k)]++;
    if (!seen.every((c) => c === 1)) allBij = false;
    if (k <= 14) { const t = C.parityTable(k); for (let r = 0; r < N; r++) if (t[r] !== naiveParity(r + N, k)) agree = false; }
  }
  ok(allBij, 'Terras bijection: for every k from 1 to 20, the 2^k residues give 2^k distinct parity vectors (naive twin)');
  ok(agree, 'the engine parityTable() matches the naive twin for every k from 1 to 14');
  // same ending, same moves, on big numbers
  let same = true;
  for (let t = 0; t < 200; t++) {
    const k = 1 + (t % 60); const a = 10n ** 40n + BigInt(t) * 7919n; const b = a + BigInt(t + 1) * 2n ** BigInt(k) * 1000003n;
    if (C.parityVector(a, k).join('') !== C.parityVector(b, k).join('')) same = false;
  }
  ok(same, 'numbers sharing their last k bits (k up to 60, 40-digit numbers) make the same first k moves');
}
{
  // dropsWithin: every member above the bound really does fall below its start within `at` steps
  let bad = 0, checked = 0;
  for (let k = 1; k <= 12; k++) {
    const N = 2 ** k;
    for (let r = 0; r < N; r++) {
      const d = C.dropsWithin(C.parityVector(BigInt(r + N), k), k);
      if (!d.at) continue;
      for (let n = r; n < 2 ** 18; n += N) {
        if (n < 2 || BigInt(n) <= d.bound) continue;
        let x = n; for (let i = 0; i < d.at; i++) x = x % 2 ? (3 * x + 1) / 2 : x / 2;
        checked++; if (!(x < n)) bad++;
      }
    }
  }
  ok(bad === 0, `every class the sieve marks as falling does fall: ${checked.toLocaleString('en-US')} numbers below 2^18 checked, ${bad} exceptions`);
}
{
  // survivor counts against OEIS A076227 (local copy, or oeis.org)
  const local = join(here, 'research/collatz/b076227.txt');
  const text = existsSync(local) ? readFileSync(local, 'utf8') : await (await fetch('https://oeis.org/A076227/b076227.txt')).text();
  const terms = new Map(text.split('\n').filter((l) => /^\d+\s+\d+/.test(l)).map((l) => { const [a, b] = l.trim().split(/\s+/); return [+a, BigInt(b)]; }));
  const K = Math.max(...terms.keys());
  const s = C.survivorCounts(K);
  let mism = 0; for (let k = 1; k <= K; k++) if (terms.has(k) && s[k - 1] !== terms.get(k)) mism++;
  ok(mism === 0 && K > 3000, `survivorCounts() matches all ${K.toLocaleString('en-US')} terms of OEIS A076227 (${mism} mismatches)`);
  // and the counts are about real residues, not only vectors: count them directly for k <= 16
  let direct = true;
  for (let k = 1; k <= 16; k++) {
    const N = 2 ** k; let alive = 0;
    for (let r = 0; r < N; r++) { let w = naiveParity(r + N, k), j = 0, dead = false; for (let i = 1; i <= k; i++) { j += (w >> (i - 1)) & 1; if (3 ** j < 2 ** i) { dead = true; break; } } if (!dead) alive++; }
    if (BigInt(alive) !== s[k - 1]) direct = false;
  }
  ok(direct, 'counting the surviving residues directly (k up to 16) gives the same numbers as the dynamic program');
  const share = (k) => (Number((s[k - 1] * 10n ** 30n) / 2n ** BigInt(k)) / 1e30).toExponential(2);
  const shown = [10, 40, 100, 500].map(share).join(' ');
  ok(shown === '6.25e-2 5.82e-3 2.39e-4 2.66e-11', `survivor share at k = 10, 40, 100, 500: ${shown} (the page prints these four)`);
}

// ── 3. change one number ────────────────────────────────────────────────────
function naiveCensus(N, q, r) {
  const loops = new Map(); const esc = [];
  for (let s = 1; s <= N; s++) {
    let x = BigInt(s); const seen = new Set();
    while (!seen.has(x) && x <= 10n ** 30n) { seen.add(x); x = x % 2n ? BigInt(q) * x + BigInt(r) : x / 2n; }
    if (x > 10n ** 30n) { esc.push(s); continue; }
    // walk the loop once to find its smallest member
    let m = x, y = x; do { y = y % 2n ? BigInt(q) * y + BigInt(r) : y / 2n; if (y < m) m = y; } while (y !== x);
    loops.set(m, (loops.get(m) || 0) + 1);
  }
  return { loops: [...loops.keys()].sort((a, b) => (a < b ? -1 : 1)).join(','), esc };
}
for (const [q, r, want] of [[3, 1, '1'], [3, -1, '1,5,17'], [5, 1, '1,13,17'], [7, 1, '1']]) {
  const e = C.census(2000, q, r), n = naiveCensus(2000, q, r);
  const eMins = e.cycles.map((c) => c.min).join(',');
  ok(eMins === n.loops && e.escaped.join(',') === n.esc.join(',') && eMins === want,
    `${q}n${r > 0 ? '+' : '−'}1, starts 1..2000: loops through ${eMins}; ${e.escaped.length} escape past 10^30 (engine and twin agree)`);
}
{
  const c = C.census(20, 3, -1).cycles.map((x) => x.cycle.length).join(',');
  ok(c === '2,5,18', `3n−1 loop lengths ${c} (page: 1 → 2, a loop of five through 5, a loop of eighteen through 17)`);
  const e5 = C.census(20, 5, 1).escaped; ok(e5.includes(7), '7 climbs past 10^30 under 5n+1 (the page says we stopped watching, not that it diverges)');
  ok(C.drift(3) < 0 && C.drift(5) > 0 && Math.abs(Math.exp(C.drift(3)) - 0.866) < 5e-4, `drift per shortcut step: 3 → ${C.drift(3).toFixed(4)}, 5 → +${C.drift(5).toFixed(4)}`);
  // n -> -n turns 3n+1 on the negatives into 3n-1 on the positives
  let mirror = true; for (let n = 1; n <= 500; n++) { const a = C.orbitOf(-n, 3, 1, 10n ** 9n, 400).path.slice(0, 60).map((x) => -x).join(','); const b = C.orbitOf(n, 3, -1, 10n ** 9n, 400).path.slice(0, 60).join(','); if (a !== b) mirror = false; }
  ok(mirror, '3n+1 run on −n is 3n−1 run on n, negated, for n = 1..500');
}

// ── 4. every loop up to length k, by a second method ────────────────────────
// For each j, walk all vectors with exactly j ones by depth-first search, carrying
// c mod D (D = |2^k − 3^j|) in plain Numbers. No fractions, no BigInt division.
function loopsModular(k) {
  const hits = [];
  for (let j = 0; j <= k; j++) {
    const Dbig = 2n ** BigInt(k) - 3n ** BigInt(j); if (Dbig === 0n) continue;
    const D = Number(Dbig < 0n ? -Dbig : Dbig); if (D === 1) { /* everything divides */ }
    const p2 = []; let t = 1 % D; for (let i = 0; i < k; i++) { p2.push(t); t = (t * 2) % D; }
    const stack = [[0, 0, 0, 0]];   // position, ones so far, c mod D, bits
    while (stack.length) {
      const [i, o, c, w] = stack.pop();
      if (i === k) { if (o === j && c === 0) hits.push({ w, j }); continue; }
      if (k - i > j - o) stack.push([i + 1, o, c, w]);
      if (o < j) stack.push([i + 1, o + 1, (Number((BigInt(c) * 3n) % BigInt(D)) + p2[i]) % D, w | (1 << i)]);
    }
  }
  return hits;
}
{
  let agree = true, all = [];
  for (let k = 1; k <= 24; k++) {
    const m = loopsModular(k).map((h) => h.w).sort((a, b) => a - b);
    if (k <= 18) { const e = C.cyclesOfLength(k).map((h) => h.w).sort((a, b) => a - b); if (e.join() !== m.join()) agree = false; }
    for (const w of m) { // recover n exactly and keep it
      let c = 0n, j = 0, p = 1n; for (let i = 0; i < k; i++) { if ((w >>> i) & 1) { c = 3n * c + p; j++; } p *= 2n; }
      all.push({ w, j, n: c / (2n ** BigInt(k) - 3n ** BigInt(j)) });
    }
  }
  ok(agree, 'the modular search and the engine cyclesOfLength() find exactly the same patterns for every length 1 to 18');
  const cyc = C.distinctCycles(all);
  const desc = cyc.map((c) => `${c.min}/p${c.period}`).join(' ');
  ok(desc === '-136/p11 -10/p3 -1/p1 0/p1 1/p2', `every loop of length 1 to 24, over all integers: ${desc}`);
  const m17 = cyc.find((c) => c.period === 11).members.map(String).join(' ');
  ok(m17.startsWith('-17 '), `the eleven-long loop, shown from its member nearest zero: ${m17}`);
  ok(cyc.filter((c) => c.min > 0n).length === 1, 'among the positive numbers, only 1 → 2 → 1');
  const w = C.cyclesOfLength(2).find((h) => h.n === 1n); ok(w && w.j === 1, 'worked example: pattern ▲▼ (k = 2, j = 1, c = 1) gives n = 1 / (4 − 3) = 1');
}

console.log(`\n${passes} passed, ${fails} failed`);
process.exit(fails ? 1 : 0);
