// WHICH ASSERTION HERE FAILS IF THE ANSWER IS SIMPLY WRONG?
// Assertions 3 and 7 pin the two published exact sizes. Assertions 4 and 8 pin the
// independently derived exact powers. Assertions 20 through 31 doctor one value in
// serialized certificate text and require the real checker to fail on the named line.

import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import {
  BINOMIAL_KIND,
  FISHER_KIND,
  binomialIntegerWeights,
  defineCertificates,
  evaluateRule,
  fisherIntegerWeights,
  parseRuleInput,
  percentLabel,
} from '../../public/tools/rule-check/engine.mjs';

const kitSource = readFileSync(new URL('../../public/_kit/certificate.js', import.meta.url), 'utf8');
const sandbox = { window: {} };
vm.runInContext(kitSource, vm.createContext(sandbox));
const C = sandbox.window.AW.certificate;
defineCertificates(C);

const binomialFixture = JSON.parse(readFileSync(new URL('./fixtures/binomial-sign-test.json', import.meta.url), 'utf8'));
const fisherFixture = JSON.parse(readFileSync(new URL('./fixtures/fisher-tea.json', import.meta.url), 'utf8'));

let passed = 0;
let failed = 0;
let assertionNumber = 0;

function test(name, fn) {
  assertionNumber++;
  try {
    fn();
    passed++;
    console.log(`${assertionNumber}. PASS ${name}`);
  } catch (error) {
    failed++;
    console.log(`${assertionNumber}. FAIL ${name}: ${error.message}`);
  }
}

function makeFromText(text) {
  const parsed = parseRuleInput(text, C);
  const evaluated = evaluateRule(parsed, C);
  return C.make(evaluated.kind, evaluated.data);
}

function integers(vector) {
  return vector.map((q) => Number(q.toString()));
}

function independentFixedPositive(q, places) {
  assert.ok(q.n >= 0n, 'independent formatter only handles nonnegative values');
  const scale = 100n * 10n ** BigInt(places);
  const rounded = (q.n * scale * 2n + q.d) / (2n * q.d);
  const digits = rounded.toString().padStart(places + 1, '0');
  return places === 0 ? digits : `${digits.slice(0, -places)}.${digits.slice(-places)}`;
}

function replaceRow(text, key, replacement) {
  const lines = text.split('\n');
  const index = lines.findIndex((line) => line.startsWith(`${key}:`));
  assert.notEqual(index, -1, `missing ${key} row in control`);
  lines[index] = `${key}: ${replacement}`;
  return lines.join('\n');
}

function replaceVectorValue(text, key, at, replacement) {
  const lines = text.split('\n');
  const index = lines.findIndex((line) => line.startsWith(`${key}:`));
  assert.notEqual(index, -1, `missing ${key} row in control`);
  const colon = lines[index].indexOf(':');
  const values = lines[index].slice(colon + 1).trim().split(/\s+/).filter(Boolean);
  assert.ok(at >= 0 && at < values.length, `${key} has no value ${at}`);
  values[at] = replacement;
  lines[index] = `${key}: ${values.join(' ')}`;
  return lines.join('\n');
}

function fault(name, cert, doctor, namedLine) {
  test(name, () => {
    const original = C.serialise(cert);
    const doctored = doctor(original);
    assert.notEqual(doctored, original, 'fault did not change the serialized text');
    const result = C.check(C.readback(doctored));
    assert.equal(result.ok, false, 'doctored certificate passed');
    assert.ok(result.lines.some((line) => !line.ok && namedLine.test(line.text)), `no failure named ${namedLine}`);
  });
}

const binomialCert = makeFromText(binomialFixture.input);
const fisherCert = makeFromText(fisherFixture.input);
const exactCert = makeFromText(`model: binomial
n: 10
p0: 0.5
p1: 0.9
rule: exact
tail: greater
alpha: 0.05`);

console.log('Published positive controls');
test('the Churvich fixture uses the published rejection counts 9 and 10', () => {
  assert.deepEqual(integers(binomialCert.data.rejection), binomialFixture.expectedRegion);
});
test('the unmodified checker passes the published binomial fixture', () => {
  assert.equal(C.check(binomialCert).ok, true);
});
test('the published binomial level is exactly 11/1024', () => {
  assert.ok(binomialCert.data.size.eq(C.Q(binomialFixture.expectedSize)));
});
test('binomial power independently expands to 10*(9/10)^9*(1/10)+(9/10)^10', () => {
  assert.ok(binomialCert.data.power.eq(C.Q(binomialFixture.expectedPower)));
});
test('the tea fixture rejects only the all-correct table', () => {
  assert.deepEqual(integers(fisherCert.data.rejection), fisherFixture.expectedRegion);
});
test('the unmodified checker passes the Fisher tea fixture', () => {
  assert.equal(C.check(fisherCert).ok, true);
});
test('Fisher tea-tasting one-sided size is exactly 1/70', () => {
  assert.ok(fisherCert.data.size.eq(C.Q(fisherFixture.expectedSize)));
});
test('tea conditional power at odds ratio 4 is independently 256/1921', () => {
  assert.ok(fisherCert.data.power.eq(C.Q(fisherFixture.expectedPower)));
});

console.log('Arithmetic controls and headline derivation');
test('all binomial probabilities sum exactly to one', () => {
  const dist = binomialIntegerWeights(37, C.Q('0.13'));
  assert.equal(dist.weights.reduce((sum, value) => sum + value, 0n), dist.denominator);
});
test('all fixed-margin Fisher probabilities sum exactly to one', () => {
  const dist = fisherIntegerWeights(14, 11, 9, C.Q('7/3'));
  assert.equal(dist.weights.reduce((sum, value) => sum + value, 0n), dist.denominator);
});
test('binomial size and its complement total exactly one', () => {
  const dist = binomialIntegerWeights(10, C.Q('0.5'));
  const rejected = dist.weights[9] + dist.weights[10];
  assert.ok(C.Q(rejected, dist.denominator).add(C.Q(dist.denominator - rejected, dist.denominator)).eq(1));
});
test('Fisher size and its complement total exactly one', () => {
  const dist = fisherIntegerWeights(4, 4, 4, C.Q(1));
  const rejected = dist.weights[4];
  assert.ok(C.Q(rejected, dist.denominator).add(C.Q(dist.denominator - rejected, dist.denominator)).eq(1));
});
test('binomial headline size is independently derived as 1.0742%', () => {
  assert.equal(independentFixedPositive(C.Q(binomialFixture.expectedSize), 4), '1.0742');
  assert.equal(percentLabel(binomialCert.data.size), '1.0742%');
});
test('binomial headline power is independently derived as 73.6099%', () => {
  assert.equal(independentFixedPositive(C.Q(binomialFixture.expectedPower), 4), '73.6099');
  assert.equal(percentLabel(binomialCert.data.power), '73.6099%');
});
test('binomial headline alpha gap is independently 3.9258 percentage points', () => {
  assert.equal(independentFixedPositive(C.Q('0.05').sub(C.Q(binomialFixture.expectedSize)), 4), '3.9258');
});
test('Fisher headline size is independently derived as 1.4286%', () => {
  assert.equal(independentFixedPositive(C.Q(fisherFixture.expectedSize), 4), '1.4286');
  assert.equal(percentLabel(fisherCert.data.size), '1.4286%');
});
test('Fisher headline power is independently derived as 13.3264%', () => {
  assert.equal(independentFixedPositive(C.Q(fisherFixture.expectedPower), 4), '13.3264');
  assert.equal(percentLabel(fisherCert.data.power), '13.3264%');
});
test('Fisher headline alpha gap is independently 3.5714 percentage points', () => {
  assert.equal(independentFixedPositive(C.Q('0.05').sub(C.Q(fisherFixture.expectedSize)), 4), '3.5714');
});

console.log('Null and truncation controls');
test('a plausible but wrong binomial region fails on the line naming the declared rule', () => {
  const wrong = replaceVectorValue(C.serialise(binomialCert), 'rejection', 0, '8');
  const result = C.check(C.readback(wrong));
  assert.equal(result.ok, false);
  assert.ok(result.lines.some((line) => !line.ok && /rejection region matches the declared rule/.test(line.text)));
});
test('removing the support row is refused before any partial certificate can pass', () => {
  const truncated = C.serialise(binomialCert).split('\n').filter((line) => !line.startsWith('support:')).join('\n');
  assert.throws(() => C.readback(truncated), /missing support/);
});

console.log('Fault table: one serialized value changed, named assertion required');
fault('binomial n 10 to 11 breaks complete support', binomialCert, (text) => replaceRow(text, 'n', '11'), /support lists every possible count/);
fault('binomial p0 0.5 to 0.4 breaks displayed size', binomialCert, (text) => replaceRow(text, 'p0', '0.4'), /displayed size equals the exact null sum/);
fault('binomial p1 0.9 to 0.8 breaks displayed power', binomialCert, (text) => replaceRow(text, 'p1', '0.8'), /displayed power equals the exact alternative sum/);
fault('exact alpha 0.05 to 0.005 breaks its constructed region', exactCert, (text) => replaceRow(text, 'threshold', '0.005'), /rejection region matches the declared rule/);
fault('one support value 8 to 7 breaks complete support', binomialCert, (text) => replaceVectorValue(text, 'support', 8, '7'), /support lists every possible count/);
fault('one declared count 9 to 8 breaks agreement with the shown region', binomialCert, (text) => replaceVectorValue(text, 'declaration', 0, '8'), /rejection region matches the declared rule/);
fault('one shown rejection count 9 to 8 breaks the declared rule', binomialCert, (text) => replaceVectorValue(text, 'rejection', 0, '8'), /rejection region matches the declared rule/);
fault('binomial size changes by one final decimal digit', binomialCert, (text) => replaceRow(text, 'size', '0.0107421876'), /displayed size equals the exact null sum/);
fault('binomial power changes by one final decimal digit', binomialCert, (text) => replaceRow(text, 'power', '0.7360989292'), /displayed power equals the exact alternative sum/);
fault('Fisher theta1 4 to 5 breaks conditional power', fisherCert, (text) => replaceRow(text, 'theta1', '5'), /displayed conditional power equals/);
fault('Fisher alpha 0.05 to 0.01 breaks its rejection region', fisherCert, (text) => replaceRow(text, 'alpha', '0.01'), /rejection region matches the declared Fisher/);
fault('Fisher rejected table 4 to 3 breaks its declared rule', fisherCert, (text) => replaceVectorValue(text, 'rejection', 0, '3'), /rejection region matches the declared Fisher/);

console.log('Boundary and convention controls');
test('strict score z greater than 1 excludes counts whose statistic equals 1', () => {
  const cert = makeFromText(`model: binomial
n: 4
p0: 0.5
p1: 0.8
rule: score
tail: two-sided
z: 1`);
  assert.deepEqual(integers(cert.data.rejection), [0, 4]);
});
test('Wald and score are not silently treated as the same rule', () => {
  const cert = makeFromText(`model: binomial
n: 4
p0: 0.5
p1: 0.8
rule: wald
tail: two-sided
z: 1`);
  assert.deepEqual(integers(cert.data.rejection), [0, 1, 3, 4]);
});
test('two-sided exact conventions are named and can produce different regions', () => {
  const base = `model: binomial\nn: 10\np0: 0.2\np1: 0.5\nrule: exact\nalpha: 0.05\ntail: `;
  const probability = makeFromText(base + 'two-sided-probability');
  const equalTail = makeFromText(base + 'two-sided-equal-tail');
  assert.notDeepEqual(integers(probability.data.rejection), integers(equalTail.data.rejection));
});
test('Fisher two-sided shorthand selects the documented probability ordering', () => {
  const cert = makeFromText(`model: fisher
n1: 4
n2: 4
m: 4
theta1: 4
rule: fisher
tail: two-sided
alpha: 0.05`);
  assert.deepEqual(integers(cert.data.rejection), [0, 4]);
  assert.equal(C.check(cert).ok, true);
});

// ── the page's OWN default example, re-derived from scratch ──────────────────────────
// A read-only audit found that the verifier never ran the input the page loads on arrival:
// its binomial assertions used a different published fixture, so the two headline numbers a
// first-time reader actually sees were checked by nothing. These are computed here from the
// binomial definition alone, with no reference to the engine's own arithmetic.
function choose(n, k) { let r = 1n; for (let i = 0n; i < BigInt(k); i++) r = (r * (BigInt(n) - i)) / (i + 1n); return r; }

test('the default 20-patient example headline size and power are re-derived independently', () => {
  const n = 20, lo = 15;
  // size at p0 = 1/2: sum of C(20,k) for k >= 15, over 2^20
  let num = 0n;
  for (let k = lo; k <= n; k++) num += choose(n, k);
  const sizeNum = num, sizeDen = 2n ** 20n;
  // power at p1 = 3/4: sum C(20,k) 3^k / 4^20
  let pnum = 0n;
  for (let k = lo; k <= n; k++) pnum += choose(n, k) * (3n ** BigInt(k));
  const powerNum = pnum, powerDen = 4n ** 20n;

  const parsed = parseRuleInput(['model: binomial', 'n: 20', 'p0: 0.5', 'p1: 0.75', 'rule: explicit', 'tail: greater', 'reject: k >= 15', 'alpha: 0.05'].join('\n'), C);
  const cert = evaluateRule(parsed, C);
  const round = C.readback(C.serialise(cert));
  assert.equal(C.check(round).ok, true, 'the default example must pass its own checker');

  // Compare as exact rationals: cross-multiply rather than divide.
  assert.equal(round.data.size.n * sizeDen, sizeNum * round.data.size.d, `size ${round.data.size.toString()} is not ${sizeNum}/${sizeDen}`);
  assert.equal(round.data.power.n * powerDen, powerNum * round.data.power.d, `power ${round.data.power.toString()} is not ${powerNum}/${powerDen}`);
  // and the decimals the page actually prints
  assert.equal(round.data.size.toFixed(7), '0.0206947');
  assert.equal(round.data.power.toFixed(7), '0.6171727');
});

// ── the degenerate rule, pinned so it cannot change quietly ───────────────────────────
// A rule whose region is empty has size 0 and power 0, which is TRUE, so the certificate
// rightly holds. What is not acceptable is for that to look like the tool having done work:
// both central sums pass without examining a single probability term. The behaviour is
// disclosed on the page and pinned here so a later change has to be deliberate.
test('an empty rejection region is accepted, reports exactly zero, and is visibly degenerate', () => {
  const parsed = parseRuleInput(['model: binomial', 'n: 20', 'p0: 0.5', 'p1: 0.75', 'rule: explicit', 'tail: greater', 'reject: k >= 21', 'alpha: 0.05'].join('\n'), C);
  const cert = evaluateRule(parsed, C);
  const round = C.readback(C.serialise(cert));
  const res = C.check(round);
  assert.equal(res.ok, true, 'size 0 and power 0 are the true answers for a rule that never rejects');
  assert.equal(round.data.size.toString(), '0');
  assert.equal(round.data.power.toString(), '0');
  assert.equal(round.data.rejection.length, 0, 'the region really is empty, which is what makes the sums vacuous');
});

console.log(`${passed} passed, ${failed} failed`);
process.exitCode = failed ? 1 : 0;
