#!/usr/bin/env node
// Verifier for the stratum page "the-bank-that-dies-at-three-percent".
//
// What this file is: the page's evidence to a stranger that the page is not lying.
// It recomputes, from scratch and independently of the page's own inline code path,
// every number the page displays at its default state, reproduces the independent
// anchor (closed form 1/L vs two separately-written numerical routes), proves the
// conservation of RWA under regrouping, executes the reconciliation battery against
// engine.mjs, and checks the page's structural honesty promises.
//
// Usage:
//   node verify-the-bank-that-dies-at-three-percent.mjs            run all checks
//   node verify-the-bank-that-dies-at-three-percent.mjs --mutate   corruption protocol
//
// Exit codes: 0 = all checks passed (and, under --mutate, the corruption was caught);
// 1 = any check failed, or zero checks ran, or a mutation went undetected.
//
// Reads the SOURCE TREE only (public/strata/... and ./engine.mjs, ./battery.json).
// It never reads a build or dist directory.

import { readFile, mkdtemp, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as engine from './engine.mjs';

const SLUG = 'the-bank-that-dies-at-three-percent';
const pageURL = new URL(`../../public/strata/${SLUG}/index.html`, import.meta.url);
const batteryURL = new URL('./battery.json', import.meta.url);

// ── harness: every assertion RETURNS a boolean that lands here ──────────────
const checks = [];
function record(name, pass, detail) {
  checks.push({ name, pass: Boolean(pass), detail: detail || '' });
  return Boolean(pass);
}
function res(name, pass, detail) { return { name, pass: Boolean(pass), detail: detail || '' }; }

// Relative tolerance comparison; the workhorse for float agreement.
function approx(a, b, tol = 1e-9) {
  return Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
}

// ── independent implementations, written separately from engine.mjs ─────────
// Deliberately different expressions and algorithms. These are the second pair
// of eyes; if engine.mjs and these disagree, that is a finding, not a nuisance.

// Naive-looking but independent form: assets after the loss minus liabilities.
function indEquity(assets, L, f) {
  return assets * (1 - f) - (assets - assets / L);
}

// Closed form via a different expression than 1/L.
function indClosed(L) {
  return Math.pow(L, -1);
}

// Generic bracketing root-find on a sign-changing g over [a, b], g(a) > 0.
function bisectGeneric(g, a, b, iters) {
  let lo = a, hi = b;
  for (let i = 0; i < iters; i++) {
    const m = (lo + hi) / 2;
    if (g(m) > 0) lo = m; else hi = m;
    if (hi - lo <= Number.EPSILON * Math.max(1, Math.abs(lo))) break;
  }
  return (lo + hi) / 2;
}

// Route two: damped fixed-point iteration on x <- x - 0.9*(1 - L*x)/L.
// Contraction factor 0.1; converges to 1/L without ever dividing 1 by L
// "as an answer" (the division by L is inside the iteration step).
function indFixedPoint(L) {
  let x = 0.5;
  for (let i = 0; i < 500; i++) {
    const g = 1 - L * x;
    // SIGN. For h(x) = 1 - L x, h'(x) = -L, so the Newton step is x + (1 - L x)/L. Written with
    // a minus it walks away from the root: from x = 0.5 at L = 10 it goes 0.86, 1.5, ... and
    // reached 1e+139 before the loop gave up. The verifier caught it because this route and the
    // closed form disagreed, which is the entire reason the anchor asks for a second route.
    x += 0.9 * g / L;
    if (Math.abs(g) < 1e-16) break;
  }
  return x;
}

// Independent RWA reductions, three groupings.
function indRwa(p) {
  return p.reduce((s, x) => s + x.exposure * x.weight, 0);
}
function indGroup(p) {
  const groups = new Map();
  for (const x of p) groups.set(x.weight, (groups.get(x.weight) || 0) + x.exposure);
  let s = 0;
  for (const [w, e] of groups) s += w * e;
  return s;
}
function indAvg(p) {
  let total = 0, weighted = 0;
  for (const x of p) { total += x.exposure; weighted += x.exposure * x.weight; }
  return total === 0 ? 0 : (weighted / total) * total;
}

// Seeded LCG so the "random" conservation cases are reproducible.
function lcg(seed) {
  let s = seed >>> 0;
  return function () {
    s = (1664525 * s + 1013904223) >>> 0;
    return s / 4294967296;
  };
}
function randPort(seed) {
  const rng = lcg(seed);
  const ws = [0, 0.35, 1, 1.5];
  const raw = [];
  for (let i = 0; i < 5; i++) raw.push(rng());
  const sum = raw.reduce((a, b) => a + b, 0);
  return raw.map((r, i) => ({
    exposure: (r / sum) * 100,
    weight: ws[Math.floor(rng() * ws.length)],
    _i: i,
  }));
}

// ── page reconciliation: recompute the page's default-state numbers ─────────
// The page ships its constants in a JSON script tag (#aw-config) precisely so a
// verifier can read them without executing page JavaScript. Every hand-worked
// literal below was computed by hand and is commented with the working.

async function pageChecks(text) {
  const out = [];

  const m = text.match(/<script type="application\/json" id="aw-config">([\s\S]*?)<\/script>/);
  out.push(res('page: embedded aw-config JSON present', Boolean(m)));
  if (!m) return out;
  let cfg;
  try { cfg = JSON.parse(m[1]); } catch (e) {
    out.push(res('page: aw-config parses as JSON', false, String(e)));
    return out;
  }
  out.push(res('page: aw-config parses as JSON', true));

  // The editor's stipulated weights, verbatim; the page must not drift from them.
  const w = cfg.buckets.map((b) => b.weight);
  out.push(res('page: weights equal the stipulation [0, 0, 0.35, 1, 1.5]',
    JSON.stringify(w) === JSON.stringify([0, 0, 0.35, 1, 1.5]), JSON.stringify(w)));

  const shareSum = cfg.buckets.reduce((s, b) => s + b.baseShare, 0);
  out.push(res('page: baseline shares sum to 100', Math.abs(shareSum - 100) < 1e-9, 'sum=' + shareSum));

  const A = cfg.assetsBn, L = cfg.defaultLeverage, f = cfg.defaultLossPct / 100;

  // Hand-worked anchors (working shown): 100/10 = 10; 1/10 = 0.1;
  // 100*(0.1 - 0.05) = 5; RWA = 5*0 + 15*0 + 40*0.35 + 35*1 + 5*1.5
  //                     = 0 + 0 + 14 + 35 + 7.5 = 56.5;
  // required = 56.5 * 0.08 = 4.52; freed at +35 pp = (56.5 - 21.5) * 0.08
  //            = 35 * 0.08 = 2.8, since the shifted book is
  //            5*0 + 50*0 + 40*0.35 + 0*1 + 5*1.5 = 21.5.
  out.push(res('page: default equity equals hand-worked 10 bn', approx(A / L, 10, 1e-12), 'A/L=' + (A / L)));
  out.push(res('page: default threshold equals hand-worked 0.1', approx(1 / L, 0.1, 1e-12)));
  out.push(res('page: default equity after 5% loss equals hand-worked 5 bn', approx(A * (1 / L - f), 5, 1e-12)));

  const port = cfg.buckets.map((b) => ({ exposure: b.baseShare, weight: b.weight }));
  const rwaHand = 0 + 0 + 40 * 0.35 + 35 * 1 + 5 * 1.5;
  out.push(res('page: baseline RWA equals hand-worked 56.5', approx(indRwa(port), rwaHand, 1e-12), 'got ' + indRwa(port)));
  out.push(res('page: required capital at 8% equals hand-worked 4.52', approx(rwaHand * 0.08, 4.52, 1e-12)));

  const shifted = port.map((p, i) =>
    i === 1 ? { exposure: p.exposure + 35, weight: p.weight } :
    i === 3 ? { exposure: p.exposure - 35, weight: p.weight } : p);
  out.push(res('page: freed capital at full shift equals hand-worked 2.8',
    approx((rwaHand - indRwa(shifted)) * 0.08, 2.8, 1e-12),
    'got ' + ((rwaHand - indRwa(shifted)) * 0.08)));

  // Cross-engine agreement on the same inputs.
  out.push(res('engine: equityAfterLoss agrees with the independent form',
    approx(engine.equityAfterLoss(A, L, f), indEquity(A, L, f), 1e-12)));
  out.push(res('engine: rwa agrees with the independent reduction',
    approx(engine.rwa(port), indRwa(port), 1e-12)));
  out.push(res('engine: bisection agrees with the closed form at default L',
    approx(engine.ruinThresholdByBisection(L), 1 / L, 1e-12)));

  // Structural honesty promises.
  out.push(res('page: no em dash (U+2014) anywhere', !text.includes('\u2014')));
  out.push(res('page: file ends with a closing </html>', text.trimEnd().endsWith('</html>')));
  const statuses = (text.match(/role="status"/g) || []).length;
  out.push(res('page: exactly one role="status" live region', statuses === 1, 'found ' + statuses));
  const deks = (text.match(/__DEK__/g) || []).length;
  out.push(res('page: zero __DEK__ placeholders left unfilled', deks === 0, 'found ' + deks));
  out.push(res('page: names its verifier command',
    text.includes(`research/${SLUG}/verify-${SLUG}.mjs`)));
  out.push(res('page: OG/Twitter titles use the middle dot separator',
    text.includes('The Bank That Dies at Three Percent · Artificial Wasteland')));

  return out;
}

// ── mutation protocol (--mutate) ────────────────────────────────────────────
// Corrupt the page's stipulated constants, CONFIRM the bytes changed, confirm the
// corrupted copy persists, confirm the sensitive checks now FAIL, then remove the
// temp copy and confirm the original is untouched. Exit non-zero if the checks
// still pass on the corrupted copy: a check that survives corruption is decoration.

async function runMutate(original) {
  console.log(`
== mutation protocol ==`);
  let mutated = original.replace('"defaultLeverage": 10', '"defaultLeverage": 9');
  mutated = mutated.replace('"weight": 0.35', '"weight": 0.36');
  record('mutate: artefact bytes actually changed', mutated !== original);
  if (mutated === original) {
    console.log('FATAL: mutation did not land; the targets were not found.');
    process.exit(1);
  }

  const dir = await mkdtemp(join(tmpdir(), 'awmut-'));
  const tmpPath = join(dir, 'index.html');
  await writeFile(tmpPath, mutated, 'utf8');
  const reread = await readFile(tmpPath, 'utf8');
  record('mutate: corrupted copy persists on disk and differs from the original', reread !== original);

  const results = await pageChecks(reread);
  const sensitive = [
    'page: default equity equals hand-worked 10 bn',
    'page: baseline RWA equals hand-worked 56.5',
  ];
  let survived = 0;
  for (const name of sensitive) {
    const r = results.find((x) => x.name === name);
    if (!r) { record(`mutate: "${name}" ran against the corrupted copy`, false, 'check missing'); continue; }
    record(`mutate: "${name}" now FAILS as expected`, !r.pass);
    if (r.pass) survived++;
  }

  await rm(dir, { recursive: true, force: true });
  const after = await readFile(pageURL, 'utf8');
  record('mutate: original source untouched after the protocol', after === original);

  if (survived > 0) {
    console.log('MUTATION WAS NOT CAUGHT: ' + survived + ' sensitive check(s) still pass.');
    finish();
  }
  console.log('Corruption caught: the sensitive checks fail on the mutated copy,');
  console.log('the temp copy is removed, and the original is byte-identical.');
  finish();
}

// ── main ────────────────────────────────────────────────────────────────────
async function main() {
  const mutateMode = process.argv.slice(2).includes('--mutate');
  const pageText = await readFile(pageURL, 'utf8');

  if (mutateMode) {
    await runMutate(pageText);
    return; // runMutate always exits
  }

  // SECTION 1. Unit tests of THIS FILE'S own helpers, against hand-worked
  // cases, before anything that depends on them. This is the check that
  // catches an aliased row or a wrong primitive under a correct algorithm.
  // NOTE: rewritten as a template literal to preserve the intended apostrophe
  // ("this file's own helpers") inside what had been a single-quoted string.
  console.log(`
== unit tests: hand-worked cases for this file's own helpers ==`);
  record('helper: approx(0.1+0.2, 0.3, 1e-12) is true (float noise absorbed)',
    approx(0.1 + 0.2, 0.3, 1e-12) === true);
  record('helper: approx(1, 2, 1e-9) is false (approx rejects real gaps)',
    approx(1, 2, 1e-9) === false);
  // Hand-worked: the root of 2 - x^2 on [1, 2] is sqrt(2) = 1.4142135623730951.
  record('helper: bisectGeneric recovers sqrt(2) on [1,2]',
    approx(bisectGeneric((x) => 2 - x * x, 1, 2, 300), Math.SQRT2, 1e-9),
    'got ' + bisectGeneric((x) => 2 - x * x, 1, 2, 300));
  // Hand-worked: 50*0.35 + 100*1 = 17.5 + 100 = 117.5.
  record('helper: indRwa hand case equals 117.5',
    approx(indRwa([{ exposure: 50, weight: 0.35 }, { exposure: 100, weight: 1 }]), 117.5, 1e-12));
  // Hand-worked: duplicate weights group cleanly: 1*(10+20) + 0.5*(30+40) = 65.
  const dup = [{ exposure: 10, weight: 1 }, { exposure: 20, weight: 1 },
               { exposure: 30, weight: 0.5 }, { exposure: 40, weight: 0.5 }];
  record('helper: indGroup hand case equals 65', approx(indGroup(dup), 65, 1e-12));
  record('helper: indAvg hand case equals 65', approx(indAvg(dup), 65, 1e-12));
  // Hand-worked: the fixed point of x <- 0.9x + 0.9/L at L=10 is 0.1.
  record('helper: indFixedPoint(10) equals 0.1', approx(indFixedPoint(10), 0.1, 1e-12));

  // SECTION 2. The independent anchor. The threshold is definitional, so there is
  // no published measurement to cite and none is invented: the anchor is that
  // THREE separately-written routes land on the same number across a sweep.
  console.log(`
== anchor: ruin threshold, closed form vs two independent numerical routes ==`);
  console.log('anchor provenance: f* = 1/L is definitional, so the independent anchors are');
  console.log('second METHODS, not published values: a bracketing bisection and a damped');
  console.log('fixed-point iteration, both written separately from engine.mjs.');
  const LEVS = [2, 5, 10, 12.5, 20, 30, 40];
  for (const Lv of LEVS) {
    const cf = indClosed(Lv);
    const bi = bisectGeneric((x) => 1 - Lv * x, 0, 1, 300);
    const fp = indFixedPoint(Lv);
    record(`anchor L=${Lv}: closed form vs independent bisection`, approx(cf, bi, 1e-12),
      `cf=${cf} bi=${bi}`);
    record(`anchor L=${Lv}: closed form vs independent fixed point`, approx(cf, fp, 1e-12),
      `fp=${fp}`);
    record(`anchor L=${Lv}: engine bisection vs independent bisection`,
      approx(engine.ruinThresholdByBisection(Lv), bi, 1e-12));
    record(`anchor L=${Lv}: engine closed form vs independent closed form`,
      approx(engine.ruinThresholdClosedForm(Lv), cf, 1e-15));
  }

  // SECTION 3. Conservation: RWA is invariant under regrouping. This is the
  // second half of the promised anchor, on portfolios including seeded randoms.
  console.log(`
== conservation: RWA identical under regrouping ==`);
  const cases = [
    { name: 'baseline book', p: [{ exposure: 5, weight: 0 }, { exposure: 15, weight: 0 },
      { exposure: 40, weight: 0.35 }, { exposure: 35, weight: 1 }, { exposure: 5, weight: 1.5 }] },
    { name: 'fully shifted book', p: [{ exposure: 5, weight: 0 }, { exposure: 50, weight: 0 },
      { exposure: 40, weight: 0.35 }, { exposure: 0, weight: 1 }, { exposure: 5, weight: 1.5 }] },
    { name: 'single asset', p: [{ exposure: 100, weight: 1.5 }] },
    { name: 'seeded random 7', p: randPort(7) },
    { name: 'seeded random 99', p: randPort(99) },
  ];
  for (const c of cases) {
    const a = indRwa(c.p), b = indGroup(c.p), d = indAvg(c.p);
    record(`conservation ${c.name}: per-position vs by-weight-group`, approx(a, b, 1e-9), `${a} vs ${b}`);
    record(`conservation ${c.name}: per-position vs mean-weight-times-total`, approx(a, d, 1e-9));
    record(`conservation ${c.name}: engine.rwa vs independent`, approx(engine.rwa(c.p), a, 1e-12));
    // Exact-integer cross-check: scale exposures to whole millions and weights
    // to whole basis points; the BigInt path must land on the float answer.
    const em = c.p.map((q) => Math.round(q.exposure * 1e6));
    const wb = c.p.map((q) => Math.round(q.weight * 1e4));
    const exact = engine.rwaExactBp(em, wb);
    const exactFloat = Number(exact) / 1e10; // million*bp -> billions
    record(`conservation ${c.name}: BigInt exact path agrees with float path`,
      approx(exactFloat, a, 1e-6), `exact=${exact.toString()} float=${a}`);
  }

  // SECTION 4. Page reconciliation.
  console.log(`
== page reconciliation: the numbers the page will display ==`);
  const pageResults = await pageChecks(pageText);
  for (const r of pageResults) record(r.name, r.pass, r.detail);

  // SECTION 5. Battery: coverage of every export, then execution.
  console.log(`
== battery: coverage and execution against engine.mjs ==`);
  let bat;
  try { bat = JSON.parse(await readFile(batteryURL, 'utf8')); }
  catch (e) { record('battery: battery.json parses', false, String(e)); finish(); return; }
  record('battery: battery.json parses and has a non-empty calls array',
    Array.isArray(bat.calls) && bat.calls.length > 0, 'calls=' + (bat.calls ? bat.calls.length : 0));

  const exported = Object.keys(engine).filter((k) => typeof engine[k] === 'function');
  const called = new Set(bat.calls.map((c) => c.fn));
  const missing = exported.filter((n) => !called.has(n));
  record('battery: every exported engine function is exercised', missing.length === 0,
    missing.length ? 'missing: ' + missing.join(', ') : 'all ' + exported.length + ' exports covered');

  for (const c of bat.calls) {
    const fn = engine[c.fn];
    if (typeof fn !== 'function') {
      record(`battery: ${c.fn} exists in engine`, false, 'not exported');
      continue;
    }
    try {
      const v = fn(...c.args);
      if (c.throws) {
        record(`battery: ${c.fn} expected to throw ${c.throws}`, false, 'did not throw');
      } else {
        const shown = typeof v === 'bigint' ? v.toString() + 'n' : JSON.stringify(v);
        record(`battery: ${c.fn} runs (${(c.note || '').slice(0, 60)}) -> ${String(shown).slice(0, 60)}`, true);
      }
    } catch (e) {
      if (c.throws) {
        record(`battery: ${c.fn} throws ${c.throws} (${(c.note || '').slice(0, 50)})`,
          e.name === c.throws, 'got ' + e.name);
      } else {
        record(`battery: ${c.fn} runs (${(c.note || '').slice(0, 60)})`, false, 'threw: ' + e.message);
      }
    }
  }

  finish();
}

function finish() {
  const failed = checks.filter((c) => !c.pass);
  console.log(`
checks: ${checks.length} run, ${checks.length - failed.length} passed, ${failed.length} failed`);
  for (const c of failed) console.log('  FAIL: ' + c.name + (c.detail ? ' :: ' + c.detail : ''));
  if (checks.length === 0) {
    console.log('FATAL: zero checks ran; a silent verifier is worse than a failing one.');
    process.exit(1);
  }
  process.exit(failed.length ? 1 : 0);
}

main().catch((e) => { console.error(e); process.exit(1); });
