import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const pagePath = path.resolve(here, '../../public/strata/one-more-odd-number/index.html');
const html = fs.readFileSync(pagePath, 'utf8');

let failures = 0;

function assert(name, condition, detail = '') {
  const marker = condition ? 'PASS' : 'FAIL';
  console.log(`${marker} ${name}${detail ? `: ${detail}` : ''}`);
  if (!condition) failures += 1;
}

function extractCore(source) {
  const startMark = '/* CORE_START */';
  const endMark = '/* CORE_END */';
  const start = source.indexOf(startMark);
  const end = source.indexOf(endMark);
  if (start < 0 || end < 0 || end <= start) throw new Error('Core markers not found');
  return source.slice(start + startMark.length, end);
}

function loadShipped(source = html) {
  const sandbox = { Map, Math, Number, BigInt };
  sandbox.globalThis = sandbox;
  vm.runInNewContext(extractCore(source), sandbox, { filename:'shipped-antihydra-core.js' });
  return sandbox.AntihydraCore;
}

const shipped = loadShipped();

function referenceRecurrence(state) {
  const oddBit = state.x & 1n;
  const nextX = (3n * state.x - oddBit) / 2n;
  return {
    x:nextX,
    b:state.b + (oddBit === 0n ? 2n : -1n),
    even:state.even + (oddBit === 0n ? 1n : 0n),
    odd:state.odd + oddBit,
    steps:state.steps + 1n
  };
}

const referenceTable = {
  A:[{ write:1, delta:1, next:'B' }, { write:1, delta:1, next:'A' }],
  B:[{ write:0, delta:-1, next:'C' }, { write:1, delta:-1, next:'E' }],
  C:[{ write:1, delta:-1, next:'D' }, { write:1, delta:-1, next:'C' }],
  D:[{ write:1, delta:-1, next:'A' }, { write:0, delta:-1, next:'B' }],
  E:[{ write:1, delta:-1, next:'F' }, { write:1, delta:1, next:'E' }],
  F:[null, { write:0, delta:1, next:'A' }]
};

function referenceMachine() {
  return { ones:new Set(), position:0, state:'A', count:0, halted:false };
}

function referenceMachineStep(machine) {
  if (machine.halted) return false;
  const symbol = machine.ones.has(machine.position) ? 1 : 0;
  const instruction = referenceTable[machine.state][symbol];
  if (instruction === null) {
    machine.halted = true;
    return false;
  }
  if (instruction.write === 1) machine.ones.add(machine.position);
  else machine.ones.delete(machine.position);
  machine.position += instruction.delta;
  machine.state = instruction.next;
  machine.count += 1;
  return true;
}

function referenceFrame(machine) {
  if (machine.halted || machine.state !== 'E' || machine.ones.has(machine.position)) return null;
  let cursor = machine.position - 1;
  let run = 0;
  while (machine.ones.has(cursor)) {
    run += 1;
    cursor -= 1;
  }
  if (run < 4) return null;
  cursor -= 1;
  let balance = 0;
  while (machine.ones.has(cursor)) {
    balance += 1;
    cursor -= 1;
  }
  const permittedLeft = cursor + 1;
  const permittedRight = machine.position - 1;
  for (const position of machine.ones) {
    if (position < permittedLeft || position > permittedRight) return null;
  }
  return { x:BigInt(run + 4), b:BigInt(balance) };
}

function referenceFrames(moveCount) {
  const machine = referenceMachine();
  const frames = [];
  let previous = -1;
  while (frames.length <= moveCount && machine.count < 1000000) {
    referenceMachineStep(machine);
    const frame = referenceFrame(machine);
    if (frame && machine.count > previous) {
      frames.push({ rawStep:machine.count, x:frame.x, b:frame.b });
      previous = machine.count;
    }
  }
  return frames;
}

assert('page core was extracted from shipped HTML', typeof shipped.recurrenceStep === 'function');
assert('exact published machine code is shipped',
  shipped.MACHINE_CODE === '1RB1RA_0LC1LE_1LD1LC_1LA0LB_1LF1RE_---0RA');

let differentialPasses = 0;
let differentialTotal = 0;
for (let seed = 1n; seed <= 256n; seed += 1n) {
  let pageState = { x:seed, b:0n, even:0n, odd:0n, steps:0n };
  let refState = { ...pageState };
  for (let step = 0; step < 96; step += 1) {
    pageState = shipped.recurrenceStep(pageState);
    refState = referenceRecurrence(refState);
    differentialTotal += 1;
    if (
      pageState.x === refState.x &&
      pageState.b === refState.b &&
      pageState.even === refState.even &&
      pageState.odd === refState.odd &&
      pageState.steps === refState.steps
    ) differentialPasses += 1;
  }
}
assert('shipped recurrence matches independent algebraic reference sweep',
  differentialPasses === differentialTotal,
  `${differentialPasses}/${differentialTotal} states`);

let canonicalPage = { x:8n, b:0n, even:0n, odd:0n, steps:0n };
const canonicalReference = [];
for (let index = 0; index < 9; index += 1) {
  canonicalReference.push(canonicalPage.x);
  canonicalPage = shipped.recurrenceStep(canonicalPage);
}
const publishedPrefix = [8n, 12n, 18n, 27n, 40n, 60n, 90n, 135n, 202n];
assert('published first nine recurrence values',
  canonicalReference.every((value, index) => value === publishedPrefix[index]),
  canonicalReference.join(', '));

const shippedRows = shipped.auditRawFrames(8);
const referenceRows = referenceFrames(8);
const frameMatches = shippedRows.length === referenceRows.length && shippedRows.every((row, index) =>
  row.rawStep === referenceRows[index].rawStep &&
  row.decodedX === referenceRows[index].x &&
  row.decodedB === referenceRows[index].b &&
  row.pass
);
assert('raw shipped simulator matches independent transition simulator',
  frameMatches,
  `${shippedRows.length} frames through raw step ${shippedRows.at(-1).rawStep}`);

const rawStepSequence = shippedRows.map(row => row.rawStep);
assert('raw frame steps are independently reproduced',
  rawStepSequence.join(',') === referenceRows.map(row => row.rawStep).join(','),
  rawStepSequence.join(', '));

const first = shippedRows[0];
assert('blank tape reaches the canonical arithmetic frame',
  first.rawStep === 11 && first.decodedX === 8n && first.decodedB === 0n,
  `step ${first.rawStep}, (${first.decodedX}, ${first.decodedB})`);

const heuristic = shipped.heuristicValue();
const referenceLog = 1073720885 * Math.log10((Math.sqrt(5) - 1) / 2);
assert('published heuristic exponent is used', heuristic.exponent === 1073720885);
assert('heuristic logarithm is independently recomputed',
  Math.abs(heuristic.log10 - referenceLog) < 1e-9,
  heuristic.log10.toFixed(6));
assert('heuristic scientific form is recomputed rather than forced to the paper mantissa',
  heuristic.power === -224394395 && heuristic.mantissa.toFixed(2) === '9.05',
  `${heuristic.mantissa.toFixed(2)} x 10^${heuristic.power}`);
assert('page visibly reports the paper approximation discrepancy',
  html.includes('4.84 x 10^-224394395') &&
  html.includes('could not reconcile the printed approximation'));

assert('published S(5) value is present and labelled as comparison',
  html.includes('S(5) = 47,176,870') && html.includes('Published comparison.'));
assert('published TNF enumeration count is present',
  html.includes('181,385,789'));
assert('reported finite trajectory is cited rather than claimed as reproduced',
  html.includes('2,147,483,648') &&
  html.includes('b = 1,073,720,884') &&
  html.includes('does not pretend to rerun'));
assert('dated informal holdout count is current and qualified',
  // Re-checked against wiki.bbchallenge.org/wiki/Holdouts on 2026-07-29: the BB(6) row is
  // 1,064 (shared 28 July 2026), superseding the 1,094 row of 29 June 2026. The wiki column
  // is headed "holdouts", not equivalence classes, so the page says holdouts.
  html.includes('1,064') && html.includes('mutable, informal'));
assert('still-open statement is visible',
  html.includes('Still open.') && html.includes('Antihydra is Collatz-like'));

class FakeElement {
  constructor(tag = 'div') {
    this.tagName = tag.toUpperCase();
    this.children = [];
    this.listeners = new Map();
    this.attributes = new Map();
    this.style = { width:'', setProperty() {} };
    this.textContent = '';
    this.className = '';
    this.disabled = false;
    this._innerHTML = '';
  }
  set innerHTML(value) {
    this._innerHTML = value;
    if (value === '') this.children = [];
  }
  get innerHTML() { return this._innerHTML; }
  appendChild(child) { this.children.push(child); return child; }
  setAttribute(name, value) { this.attributes.set(name, String(value)); }
  addEventListener(type, listener) {
    if (!this.listeners.has(type)) this.listeners.set(type, []);
    this.listeners.get(type).push(listener);
  }
  fire(type) {
    for (const listener of this.listeners.get(type) || []) listener({ type, target:this });
  }
}

function runUiSmoke() {
  const elements = new Map();
  for (const match of html.matchAll(/\bid="([^"]+)"/g)) {
    elements.set(match[1], new FakeElement());
  }
  const document = {
    getElementById(id) {
      if (!elements.has(id)) elements.set(id, new FakeElement());
      return elements.get(id);
    },
    createElement(tag) { return new FakeElement(tag); }
  };
  const scripts = [...html.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/g)]
    .filter(match => !/\bsrc=/.test(match[1]) && !/application\/ld\+json/.test(match[1]));
  if (scripts.length !== 1) throw new Error(`Expected one executable inline script, found ${scripts.length}`);
  const sandbox = {
    document,
    Map,
    Math,
    Number,
    BigInt,
    console,
    setTimeout(callback) { callback(); return 1; },
    matchMedia() { return { matches:true }; }
  };
  sandbox.window = sandbox;
  sandbox.globalThis = sandbox;
  vm.runInNewContext(scripts[0][2], sandbox, { filename:'shipped-antihydra-app.js' });
  return { elements, sandbox };
}

const ui = runUiSmoke();
assert('full shipped application initializes live recurrence readout',
  ui.elements.get('orbit-x').textContent === '8' &&
  ui.elements.get('check-prefix').textContent.startsWith('8, 12, 18, 27'));
ui.elements.get('orbit-step').fire('click');
assert('Step control executes the recurrence',
  ui.elements.get('orbit-steps').textContent === '1' &&
  ui.elements.get('orbit-balance').textContent === '2');
ui.elements.get('raw-frame').fire('click');
assert('raw-machine control reaches and decodes the first frame',
  ui.elements.get('machine-status').textContent.includes('x = 8, b = 0'));
ui.elements.get('raw-audit').fire('click');
assert('raw audit control renders all finite matches',
  ui.elements.get('audit-note').textContent.includes('9 of 9 recognizable frames match'));
assert('visible heuristic readout shows the recomputation',
  ui.elements.get('check-heuristic').textContent.includes('9.05 x 10^-224394395'));

const mutatedHtml = html.replace(
  "x:state.x + state.x / 2n,",
  "x:state.x + state.x / 2n + 1n,"
);
let mutationCaught = false;
try {
  const mutated = loadShipped(mutatedHtml);
  let state = { x:8n, b:0n, even:0n, odd:0n, steps:0n };
  let reference = { ...state };
  for (let index = 0; index < 4; index += 1) {
    state = mutated.recurrenceStep(state);
    reference = referenceRecurrence(reference);
    if (state.x !== reference.x) {
      mutationCaught = true;
      break;
    }
  }
} catch {
  mutationCaught = true;
}
assert('mutation test catches a perturbed shipped recurrence', mutationCaught,
  'validated by changing the next-x rule in memory, then restoring the original');

assert('page contains no em dash', !html.includes('\u2014'));
assert('page contains no en dash', !html.includes('\u2013'));
assert('page has load-bearing closing tags', html.trimEnd().endsWith('</body>\n</html>'));

if (failures > 0) {
  console.error(`FAILED ${failures} assertion${failures === 1 ? '' : 's'}`);
  process.exit(1);
}

console.log('ALL ASSERTIONS PASSED');
