#!/usr/bin/env node
// Run from any cwd. Uses only Node built-ins and the page's own engine and HTML.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { analyse, noRestartMean, ensemble, tick, advance } from '../../public/strata/the-progress-you-throw-away/engine.mjs';

let checks = 0;
const ok = (condition, message) => { assert.ok(condition, message); checks++; };
const close = (a, b, message, tolerance = 2e-10) => ok(Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(b)), `${message}: ${a} vs ${b}`);

// Independent integer path counts. Absorbed strings continue to fork as labels,
// so every row has exactly 2^t equally likely coin strings. There are no floats
// in the independent numerator, denominator, reward, or survival calculation.
function counted(start, target, limit) {
  let counts = Array(target + 1).fill(0n); counts[start] = 1n;
  let denom = 1n, work = 0n;
  const rows = [];
  for (let t = 1; t <= limit; t++) {
    const alive = counts.slice(0, target).reduce((a, b) => a + b, 0n);
    work = 2n * (work + alive);
    const next = Array(target + 1).fill(0n);
    for (let x = 0; x <= target; x++) {
      if (x === target) next[target] += 2n * counts[x];
      else { next[Math.max(0, x - 1)] += counts[x]; next[x + 1] += counts[x]; }
    }
    counts = next; denom *= 2n;
    assert.equal(counts.reduce((a, b) => a + b, 0n), denom);
    rows.push({ denom, work, hits: counts[target], alive: denom - counts[target] });
  }
  return rows;
}

// A second formulation for small cases: solve the full position × timer Markov
// chain by Gaussian elimination. Reset cost appears as a reward on failed resets;
// no renewal quotient or survival sum is used by this oracle.
function linearMean(start, target, cutoff, cost) {
  const n = target * cutoff;
  const a = Array.from({ length: n }, (_, i) => {
    const row = new Float64Array(n + 1); row[i] = 1; row[n] = 1; return row;
  });
  for (let age = 0; age < cutoff; age++) for (let x = 0; x < target; x++) {
    const row = a[age * target + x];
    for (const next of [Math.max(0, x - 1), x + 1]) {
      if (next === target) continue;
      if (age + 1 === cutoff) { row[start] -= .5; row[n] += .5 * cost; }
      else row[(age + 1) * target + next] -= .5;
    }
  }
  for (let col = 0; col < n; col++) {
    let pivot = col;
    for (let r = col + 1; r < n; r++) if (Math.abs(a[r][col]) > Math.abs(a[pivot][col])) pivot = r;
    assert.ok(Math.abs(a[pivot][col]) > 1e-14);
    [a[col], a[pivot]] = [a[pivot], a[col]];
    const v = a[col][col];
    for (let j = col; j <= n; j++) a[col][j] /= v;
    for (let r = 0; r < n; r++) if (r !== col) {
      const f = a[r][col];
      for (let j = col; j <= n; j++) a[r][j] -= f * a[col][j];
    }
  }
  return a[start][n];
}

for (let target = 2; target <= 10; target++) for (let start = 0; start < target; start++) {
  const counts = counted(start, target, 32);
  for (const cost of [0, 3]) {
    const result = analyse(start, cost, 32, target);
    for (let k = 0; k < counts.length; k++) {
      const c = counts[k], row = result.rows[k];
      close(row.success, Number(c.hits) / Number(c.denom), 'success from integer strings');
      close(row.work, Number(c.work) / Number(c.denom), 'work from integer strings');
      if (c.hits === 0n) ok(row.mean === Infinity, 'unreachable cutoff cannot finish');
      else close(row.mean, Number(c.work + BigInt(cost) * c.alive) / Number(c.hits), 'restart mean from integer strings');
      close(row.work + row.survival * row.residual, result.baseline, 'total expectation with conditional residual');
    }
  }
  // Baseline satisfies the full hitting-time equations, including the sticky wall.
  const mean = noRestartMean(start, target);
  const left = noRestartMean(Math.max(0, start - 1), target);
  const right = start + 1 === target ? 0 : noRestartMean(start + 1, target);
  close(mean, 1 + (left + right) / 2, 'baseline Bellman equation');
}

// Literal enumeration of every coin word guards the counting oracle's conventions.
for (const [target, start, length] of [[3, 0, 8], [4, 2, 10], [6, 4, 12]]) {
  let hits = 0, work = 0;
  for (let word = 0; word < 2 ** length; word++) {
    let x = start, t = 0;
    while (x < target && t < length) { x = Math.max(0, x + ((word >> t & 1) ? 1 : -1)); t++; }
    hits += x === target ? 1 : 0; work += t;
  }
  const row = counted(start, target, length).at(-1);
  ok(row.hits === BigInt(hits) && row.work === BigInt(work), 'literal coin words match exact oracle');
}
for (const [target, start, cutoff, cost] of [[3, 1, 4, 0], [3, 1, 5, 3], [4, 2, 6, 2], [4, 0, 7, 1]]) {
  close(analyse(start, cost, cutoff, target).rows.at(-1).mean, linearMean(start, target, cutoff, cost), 'expanded Markov-chain solve');
}

const anchor = counted(16, 20, 12).at(-1);
ok(anchor.hits === 1093n && anchor.alive === 3003n && anchor.work === 44288n && anchor.denom === 4096n, 'default exact certificate');
const base = analyse(16, 0);
ok(base.baseline === 148 && base.best.cutoff === 12, 'default and best on declared 1..240 grid');
close(base.rows[11].mean, 44288 / 1093, 'default displayed mean');
close(base.rows[11].threshold, 117476 / 3003, 'fixed-cutoff cost boundary');
ok(analyse(16, 40).rows[11].mean > 148, 'cost 40 destroys the fixed-12 advantage');
ok(analyse(2, 0).best.mean > noRestartMean(2), 'far-start control: no tested cutoff helps');
ok(analyse(16, 0).rows[2].mean === Infinity, 'three moves cannot travel four edges');
close(analyse(19, 0).rows[0].mean, 2, 'one-step geometric anchor');
close(advance(new Float64Array([1, 0])).mass[0], .5, 'left coin at wall stays put');

for (const cost of [0, 3]) {
  const state = ensemble(16, 12, cost);
  const r = analyse(16, cost).rows[11];
  for (let t = 0; t < 12; t++) tick(state);
  close(state.arrived, r.success, 'ensemble at first cutoff');
  ok(state.age === 0 && state.cooling === cost, 'reset clock convention');
  for (let t = 0; t < cost; t++) tick(state);
  close(state.arrived, r.success, 'no arrivals during reset cost');
  for (let t = 0; t < 12; t++) tick(state);
  close(state.arrived, 1 - r.survival ** 2, 'second independent attempt');
  close(state.arrived + state.mass.reduce((a, b) => a + b, 0), 1, 'ensemble conserves mass');
}
const short = ensemble(16, 3, 0);
for (let t = 0; t < 1000; t++) tick(short);
ok(short.arrived === 0, 'impossible timer never produces a simulated arrival');
for (const bad of [-1, 20, 1.5, NaN]) {
  assert.throws(() => analyse(bad), RangeError); checks++;
}

// Page coupling: the static claims are read from the actual reader-facing HTML.
const html = readFileSync(new URL('../../public/strata/the-progress-you-throw-away/index.html', import.meta.url), 'utf8');
function printed(id) {
  const match = html.match(new RegExp(`id="${id}"[^>]*>([^<]+)<`));
  assert.ok(match, `missing page claim ${id}`);
  return Number(match[1].replaceAll(',', ''));
}
close(printed('anchor-baseline'), base.baseline, 'page baseline');
close(printed('anchor-reset'), Math.round(base.rows[11].mean * 100) / 100, 'page restart mean');
close(printed('anchor-threshold'), Math.round(base.rows[11].threshold * 100) / 100, 'page cost threshold');
ok(html.includes('1093/4096') && html.includes('3003/4096') && html.includes('173/16'), 'page exact fractions');
ok(html.includes('1 through 240') && html.includes('not a global optimum'), 'page bounds its optimisation claim');
ok(html.includes('arrival on the final step counts'), 'page states tie convention');
console.log(`PASS ${checks} checks: integer path counts, literal enumeration, expanded Markov chain, boundary cases, ensemble clock, and shipped-page claims.`);
console.log('Default: no restart = 148; cutoff 12, cost 0 = 44288/1093 = 40.519670631290026.');
console.log('Fixed-cutoff cost threshold = 117476/3003 = 39.11954711954712.');
