import assert from 'node:assert/strict';
import crypto from 'node:crypto';
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 root = path.resolve(here, '../..');
const htmlPath = path.join(root, 'public/strata/the-promise-that-cannot-be-broken/index.html');
const kitPath = path.join(root, 'public/_kit/precommit.js');
const html = fs.readFileSync(htmlPath, 'utf8');

const BETA = 0.5;
const DEFAULT_T = 48;
const DEFAULT_N = 8;
const ANCHOR_T = 12;

const expertNames = [
  'always LEFT',
  'always RIGHT',
  'alternate L/R',
  'alternate R/L',
  'copy your last',
  'oppose your last',
  'period L/L/R',
  'fixed tape R/L/R/R/L/L/R/L',
];

function expertPredictions(round, history) {
  const last = history.length ? history[history.length - 1] : 0;
  const tape = [1, 0, 1, 1, 0, 0, 1, 0];
  return [
    0,
    1,
    round % 2,
    1 - (round % 2),
    last,
    1 - last,
    [0, 0, 1][round % 3],
    tape[round % tape.length],
  ];
}

class WeightedMajority {
  constructor(n = DEFAULT_N, beta = BETA, update = true) {
    this.n = n;
    this.beta = beta;
    this.update = update;
    this.weights = Array(n).fill(1);
    this.mistakes = Array(n).fill(0);
    this.history = [];
    this.masterMistakes = 0;
  }
  votes() {
    return expertPredictions(this.history.length, this.history).slice(0, this.n);
  }
  predict() {
    const guesses = this.votes();
    let left = 0;
    let right = 0;
    guesses.forEach((guess, index) => {
      if (guess === 0) left += this.weights[index];
      else right += this.weights[index];
    });
    return left >= right ? 0 : 1;
  }
  observe(actual) {
    const prediction = this.predict();
    const guesses = this.votes();
    if (prediction !== actual) this.masterMistakes += 1;
    guesses.forEach((guess, index) => {
      if (guess !== actual) {
        this.mistakes[index] += 1;
        if (this.update) this.weights[index] *= this.beta;
      }
    });
    this.history.push(actual);
  }
  bestMistakes() {
    return Math.min(...this.mistakes);
  }
}

function theoremMistakeBound(bestMistakes, n, beta = BETA) {
  return (bestMistakes * Math.log(1 / beta) + Math.log(n)) / Math.log(2 / (1 + beta));
}

function sealedHorizonMistakeBound(T, n, beta = BETA) {
  return theoremMistakeBound(Math.floor(T / 2), n, beta);
}

function sealedRegretBound(T, n, beta = BETA) {
  return sealedHorizonMistakeBound(T, n, beta) - Math.floor(T / 2);
}

function runSequence(sequence, n = DEFAULT_N, update = true) {
  const machine = new WeightedMajority(n, BETA, update);
  for (const actual of sequence) machine.observe(actual);
  const best = machine.bestMistakes();
  return {
    machine,
    M: machine.masterMistakes,
    best,
    regret: machine.masterMistakes - best,
    bound: theoremMistakeBound(best, n),
  };
}

function bits(value, length) {
  return Array.from({ length }, (_, index) => (value >> (length - index - 1)) & 1);
}

function exhaustiveAnchor() {
  let worstRatio = -Infinity;
  let witness = null;
  let maxRegret = -Infinity;
  for (let value = 0; value < 2 ** ANCHOR_T; value += 1) {
    const sequence = bits(value, ANCHOR_T);
    const result = runSequence(sequence);
    assert.ok(result.M <= result.bound + 1e-12, `published bound failed on ${sequence.join('')}`);
    const additive = result.bound - result.best;
    const ratio = additive > 0 ? result.regret / additive : 0;
    if (ratio > worstRatio) {
      worstRatio = ratio;
      witness = { sequence, ...result };
    }
    maxRegret = Math.max(maxRegret, result.regret);
  }
  return { cases: 2 ** ANCHOR_T, worstRatio, witness, maxRegret };
}

const constant241 = Math.log(2) / Math.log(4 / 3);
assert.ok(Math.abs(constant241 - 2.409420839653209) < 1e-14);

for (const [T, n] of [[12, 4], [24, 8], [64, 8], [100, 6]]) {
  const bestCap = Math.floor(T / 2);
  const direct = (bestCap * Math.log(2) + Math.log(n)) / Math.log(4 / 3);
  assert.ok(Math.abs(sealedHorizonMistakeBound(T, n) - direct) < 1e-12);
}

const anchor = exhaustiveAnchor();
assert.equal(anchor.cases, 4096);
assert.ok(anchor.worstRatio > 0.15, `tightness witness too weak: ${anchor.worstRatio}`);

let rngState = 0x6d2b79f5;
function seededBit() {
  rngState ^= rngState << 13;
  rngState ^= rngState >>> 17;
  rngState ^= rngState << 5;
  return rngState & 1;
}

for (let sample = 0; sample < 1500; sample += 1) {
  const sequence = Array.from({ length: 64 }, seededBit);
  const result = runSequence(sequence);
  assert.ok(result.M <= result.bound + 1e-12, `random sweep failed at sample ${sample}`);
}

for (const sequence of [
  Array(96).fill(0),
  Array(96).fill(1),
  Array.from({ length: 96 }, (_, i) => i % 2),
  Array.from({ length: 96 }, (_, i) => [0, 0, 1][i % 3]),
]) {
  const result = runSequence(sequence);
  assert.ok(result.M <= result.bound + 1e-12);
}

const adversarialMachine = new WeightedMajority();
for (let round = 0; round < 64; round += 1) {
  adversarialMachine.observe(1 - adversarialMachine.predict());
}
assert.equal(adversarialMachine.masterMistakes, 64);
assert.ok(adversarialMachine.masterMistakes <= theoremMistakeBound(adversarialMachine.bestMistakes(), DEFAULT_N));

let brokenWitness = null;
for (let length = 1; length <= 18 && !brokenWitness; length += 1) {
  for (let value = 0; value < 2 ** length; value += 1) {
    const sequence = bits(value, length);
    const result = runSequence(sequence, DEFAULT_N, false);
    if (result.M > result.bound + 1e-12) {
      brokenWitness = { sequence, ...result };
      break;
    }
  }
}
assert.ok(brokenWitness, 'negative control failed to expose the no-update mutation');

const kitContext = {
  crypto: crypto.webcrypto,
  TextEncoder,
  Uint8Array,
  Uint32Array,
  Math,
  console,
  globalThis: null,
};
kitContext.globalThis = kitContext;
vm.createContext(kitContext);
vm.runInContext(fs.readFileSync(kitPath, 'utf8'), kitContext);
const controlMachine = new WeightedMajority();
const chance = kitContext.AW.precommit.chanceControl(controlMachine, 16384, [0, 1]);
const chanceWide = kitContext.AW.precommit.ci(chance.hits, chance.n, 0.999999);
assert.ok(Math.abs(chance.rate - 0.5) < 0.015, `CSPRNG control too far from chance: ${chance.rate}`);
assert.ok(chanceWide.lo <= 0.5 && chanceWide.hi >= 0.5, `99.9999% interval missed 0.5: ${chanceWide.lo}, ${chanceWide.hi}`);
assert.ok(controlMachine.masterMistakes <= theoremMistakeBound(controlMachine.bestMistakes(), DEFAULT_N));

const predictable = runSequence(Array(256).fill(0));
assert.ok(predictable.M <= 4, `predictable control made ${predictable.M} mistakes`);

const defaultBound = sealedRegretBound(DEFAULT_T, DEFAULT_N);
const defaultActualCap = Math.floor(defaultBound);
const witnessBits = anchor.witness.sequence.join('');
const brokenBits = brokenWitness.sequence.join('');

for (const required of [
  'Littlestone and Warmuth, Theorem 2.1 and Corollary 2.1',
  'Freund and Schapire, Theorem 2',
  'Cesa-Bianchi and Lugosi, Theorem 2.2',
  'Cesa-Bianchi and Lugosi, Theorem 3.7',
  `data-anchor-cases="${anchor.cases}"`,
  `data-anchor-horizon="${ANCHOR_T}"`,
  `data-default-t="${DEFAULT_T}"`,
  `data-default-n="${DEFAULT_N}"`,
  `data-beta="${BETA}"`,
  `data-default-bound="${defaultBound.toFixed(6)}"`,
  `data-default-integer-cap="${defaultActualCap}"`,
  `data-anchor-witness="${witnessBits}"`,
  'The comparator is fixed before the sequence begins.',
  'The promise is not accuracy.',
]) assert.ok(html.includes(required), `HTML missing recomputed string: ${required}`);

assert.match(html, /<script src="\/_kit\/precommit\.js"><\/script>/);
assert.match(html, /AW\.precommit\.seal\(/);
assert.match(html, /AW\.precommit\.revealText\(/);
assert.match(html, /AW\.precommit\.verify\(/);
assert.match(html, /AW\.precommit\.shellCommand\(/);
assert.match(html, /AW\.precommit\.chanceControl\(/);
assert.equal((html.match(/<script\b/g) || []).length, (html.match(/<\/script>/g) || []).length);
assert.match(html, /<\/body>\s*<\/html>\s*$/);

const forbiddenRuntime = /(?:src|href)\s*=\s*["']https?:\/\//i;
const body = html.slice(html.indexOf('<body'));
assert.doesNotMatch(body.replace(/<a\b[^>]*>[\s\S]*?<\/a>/gi, ''), forbiddenRuntime);
assert.doesNotMatch(html, /fetch\s*\(|XMLHttpRequest|sendBeacon|WebSocket\s*\(/);
assert.ok(!html.includes(String.fromCodePoint(0x2014)), 'HTML contains a forbidden em dash');

console.log('PASS the-promise-that-cannot-be-broken');
console.log(`published anchor: beta=1/2 constant ${constant241.toFixed(12)}, ${anchor.cases} sequences of length ${ANCHOR_T}`);
console.log(`tightness witness: ${witnessBits}, regret ${anchor.witness.regret}, additive theorem allowance ${(anchor.witness.bound - anchor.witness.best).toFixed(6)}, ratio ${(100 * anchor.worstRatio).toFixed(1)}%`);
console.log(`negative control: no-update mutation fails on ${brokenBits}, M=${brokenWitness.M}, best=${brokenWitness.best}, bound=${brokenWitness.bound.toFixed(6)}`);
console.log(`chance control: ${chance.hits}/${chance.n} hits, ${(100 * chance.rate).toFixed(2)}%, 95% CI ${(100 * chance.ci.lo).toFixed(2)}% to ${(100 * chance.ci.hi).toFixed(2)}%`);
console.log(`predictable control: ${256 - predictable.M}/256 correct`);
