#!/usr/bin/env node
// Verifier for "The Crossing Where Direct Current Wins".
//
// Recomputes every number the page displays, independently of the page's own
// code path, and compares. Reads the source tree only (engine.mjs and the
// page's index.html); never touches any build or dist output.
//
// Usage:
//   node verify-the-crossing-where-direct-current-wins.mjs            run all checks
//   node verify-the-crossing-where-direct-current-wins.mjs --mutate   corrupt engine.mjs
//                                                                     in a temp copy and
//                                                                     confirm the checks notice
//
// Exit codes: 0 all checks passed; 1 one or more checks failed (or zero
// checks ran, which is itself a failure); 2 harness/setup error.

import { readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const SLUG = 'the-crossing-where-direct-current-wins';
const ENGINE_PATH = join(HERE, 'engine.mjs');
const PAGE_PATH = join(HERE, '..', '..', 'public', 'strata', SLUG, 'index.html');
const NL = String.fromCharCode(10);

import * as engine from './engine.mjs';

// ── the harness ───────────────────────────────────────────────────────────
// Every assertion RETURNS a boolean that is inspected here. Nothing asserts
// by throwing alone; risky regions are wrapped so a throw scores as a
// failure, never as a silent pass.

let passed = 0;
let failed = 0;
const failureLines = [];

function check(name, cond, detail) {
  if (cond) { passed++; return true; }
  failed++;
  const line = 'FAIL ' + name + (detail ? ' :: ' + detail : '');
  failureLines.push(line);
  process.stdout.write(line + NL);
  return false;
}

function tryCheck(name, fn, detail) {
  try {
    return check(name, fn() === true, detail);
  } catch (err) {
    return check(name, false, 'threw: ' + (err && err.message ? err.message : String(err)));
  }
}

function relDiff(a, b) {
  return Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b), 1e-300);
}

// ── independent implementations ───────────────────────────────────────────
// Written from scratch for this verifier, deliberately structured differently
// from engine.mjs (opposite sign conventions, fixed-iteration bisection, no
// shared helpers). These are the second methods the anchors rest on.

function localBreakEven(aAc, bAc, aDc, bDc) {
  if (!(bAc > bDc) || !(aDc > aAc)) return null;
  return (aDc - aAc) / (bAc - bDc);
}

function localBisect(f, lo, hi, iters = 300) {
  let a = lo, b = hi;
  const fa = f(lo);
  for (let i = 0; i < iters; i++) {
    const m = 0.5 * (a + b);
    const fm = f(m);
    if (fm === 0) return m;
    if ((fa < 0) === (fm < 0)) { a = m; } else { b = m; }
  }
  return 0.5 * (a + b);
}

// Sign convention deliberately opposite to engine.breakEvenBisection:
// this is (AC minus DC), increasing, bracket grown while negative.
function localRootFind(aAc, bAc, aDc, bDc) {
  if (!(bAc > bDc) || !(aDc > aAc)) return null;
  const f = (d) => (aAc - aDc) + (bAc - bDc) * d;
  let hi = 1;
  while (f(hi) < 0) hi *= 2;
  return localBisect(f, 0, hi);
}

const LOCAL_EPS0 = 8.8541878128e-12;

function localRate(cPerM, vPh, hz) {
  return 2 * Math.PI * hz * cPerM * vPh;
}
function localL0(iMax, cPerM, vPh, hz) {
  const r = localRate(cPerM, vPh, hz);
  return r > 0 ? iMax / r : Infinity;
}
function localL0Bisect(iMax, cPerM, vPh, hz) {
  const g = (L) => localRate(cPerM, vPh, hz) * L - iMax;
  let hi = 1;
  while (g(hi) < 0) hi *= 2;
  return localBisect(g, 0, hi);
}
function localPower(iMax, iCh, vPh) {
  const h = iMax * iMax - iCh * iCh;
  return h > 0 ? 3 * vPh * Math.sqrt(h) : 0;
}
function localCoax(epsR, ri, ro) {
  return 2 * Math.PI * LOCAL_EPS0 * epsR / Math.log(ro / ri);
}

// ── section 1: unit-test the small pure helpers FIRST ─────────────────────
// Hand-worked cases. If these fail, nothing downstream is trustworthy.

process.stdout.write(NL + '== 1. helper unit tests (hand-worked) ==' + NL);

tryCheck('bisect solves x^2 = 4 on [0,5]', () =>
  Math.abs(localBisect((x) => x * x - 4, 0, 5) - 2) < 1e-9);
tryCheck('bisect solves 10 - x = 0 on [0,20]', () =>
  Math.abs(localBisect((x) => 10 - x, 0, 20) - 10) < 1e-9);
tryCheck('root-find reproduces hand division 300/0.4 = 750', () =>
  Math.abs(localRootFind(100, 1, 400, 0.6) - 750) < 750 * 1e-9);
tryCheck('root-find reproduces hand division 250/0.3', () =>
  Math.abs(localRootFind(50, 0.5, 300, 0.2) - (250 / 0.3)) < (250 / 0.3) * 1e-9);
tryCheck('root-find refuses infeasible params (parallel per-km)', () =>
  localRootFind(100, 1, 400, 1) === null);
tryCheck('root-find refuses infeasible params (DC cheaper upfront)', () =>
  localRootFind(400, 0.6, 100, 1) === null);
tryCheck('microfarad/km to farad/m: 0.25 becomes 2.5e-10', () =>
  relDiff(engine.ufPerKmToFPerM(0.25), 2.5e-10) < 1e-12);
tryCheck('analytic anchor: P(L0/2) / P0 = sqrt(3)/2', () => {
  const vPh = 220000 / Math.sqrt(3);
  const cM = 2.5e-10;
  const iMax = 800;
  const l0 = localL0(iMax, cM, vPh, 50);
  const ratio = localPower(iMax, localRate(cM, vPh, 50) * (l0 / 2), vPh) /
                localPower(iMax, 0, vPh);
  return Math.abs(ratio - Math.sqrt(3) / 2) < 1e-12;
});
tryCheck('analytic anchor: charging current at L0/2 is exactly I_max/2', () => {
  const vPh = 220000 / Math.sqrt(3);
  const cM = 2.5e-10;
  const iMax = 800;
  const l0 = localL0(iMax, cM, vPh, 50);
  return Math.abs(localRate(cM, vPh, 50) * (l0 / 2) - iMax / 2) < 1e-9;
});

// ── section 2: the independent anchors ────────────────────────────────────

process.stdout.write(NL + '== 2. anchor A: land break-even, closed form vs root-find ==' + NL);
process.stdout.write('   second method: bisection on the cost difference, written fresh' + NL);
process.stdout.write('   in this verifier with the opposite sign convention; no formula shared.' + NL);

const LAND_GRID = [];
for (const aAc of [50, 100, 200])
  for (const aDc of [250, 400, 600])
    for (const bAc of [0.5, 1.0, 1.5])
      for (const bDc of [0.2, 0.6, 0.9])
        LAND_GRID.push([aAc, bAc, aDc, bDc]);

let landCombos = 0;
for (const [aAc, bAc, aDc, bDc] of LAND_GRID) {
  landCombos++;
  const tag = 'land[' + aAc + ',' + bAc + ',' + aDc + ',' + bDc + ']';
  const lt = localBreakEven(aAc, bAc, aDc, bDc);
  const lr = localRootFind(aAc, bAc, aDc, bDc);
  const ge = engine.breakEvenClosedForm(aAc, bAc, aDc, bDc);
  const gb = engine.breakEvenBisection(aAc, bAc, aDc, bDc);
  tryCheck(tag + ' feasibility flag: local vs engine closed', () =>
    ((lt == null) === (ge.dStarKm == null)));
  tryCheck(tag + ' feasibility flag: local vs engine bisection', () =>
    ((lt == null) === (gb.dStarKm == null)));
  if (lt != null) {
    tryCheck(tag + ' closed form vs local root-find (1e-9 rel)', () =>
      relDiff(lt, lr) < 1e-9);
    tryCheck(tag + ' engine closed vs local (1e-9 rel)', () =>
      relDiff(lt, ge.dStarKm) < 1e-9);
    tryCheck(tag + ' engine bisection vs local (1e-9 rel)', () =>
      relDiff(lt, gb.dStarKm) < 1e-9);
  }
}
process.stdout.write('   swept ' + landCombos + ' parameter combinations.' + NL);

process.stdout.write(NL + '== 3. anchor B: submarine L0, direct solution vs monotone bisection ==' + NL);
process.stdout.write('   second method: bisection on the ampacity balance' + NL);
process.stdout.write('   I_max - omega*C*V*L, written fresh here; tolerance 1e-9 relative.' + NL);

const SEA_GRID = [];
for (const kv of [66, 132, 220, 400])
  for (const uf of [0.15, 0.25, 0.35])
    for (const im of [500, 800, 1200])
      SEA_GRID.push([kv, uf, im]);

let seaCombos = 0;
for (const [kv, uf, im] of SEA_GRID) {
  seaCombos++;
  const vPh = kv * 1000 / Math.sqrt(3);
  const cM = engine.ufPerKmToFPerM(uf);
  const tag = 'sea[' + kv + 'kV,' + uf + ',' + im + 'A]';
  const lt = localL0(im, cM, vPh, 50);
  const lb = localL0Bisect(im, cM, vPh, 50);
  tryCheck(tag + ' local direct vs local bisection (1e-9 rel)', () =>
    relDiff(lt, lb) < 1e-9);
  tryCheck(tag + ' engine closed vs local (1e-9 rel)', () =>
    relDiff(lt, engine.zeroDeliveryLengthMetres(im, cM, vPh, 50)) < 1e-9);
  tryCheck(tag + ' engine bisection vs local (1e-9 rel)', () =>
    relDiff(lt, engine.zeroDeliveryBisection(im, cM, vPh, 50).lengthM) < 1e-9);
}
process.stdout.write('   swept ' + seaCombos + ' cable regimes.' + NL);

process.stdout.write(NL + '== 4. spot anchors: power, capacitance, winner boundary ==' + NL);

{
  const vPh = 220000 / Math.sqrt(3);
  for (const frac of [0, 0.25, 0.5, 0.9]) {
    const ic = 800 * frac;
    tryCheck('power at ' + (frac * 100) + '% charging: engine vs local (1e-12 rel)', () =>
      relDiff(engine.deliverablePowerWatts(800, ic, vPh), localPower(800, ic, vPh)) < 1e-12);
  }
  tryCheck('power at exactly the ampacity limit is 0', () =>
    engine.deliverablePowerWatts(800, 800, vPh) === 0);
  tryCheck('power over the ampacity limit is 0, never negative', () =>
    engine.deliverablePowerWatts(800, 1000, vPh) === 0);
  tryCheck('coax capacitance, XLPE-like geometry: engine vs local (1e-12 rel)', () =>
    relDiff(engine.coaxCapacitancePerMetre(2.3, 0.008, 0.019),
            localCoax(2.3, 0.008, 0.019)) < 1e-12);
  tryCheck('coax capacitance, second geometry: engine vs local (1e-12 rel)', () =>
    relDiff(engine.coaxCapacitancePerMetre(2.1, 0.010, 0.025),
            localCoax(2.1, 0.010, 0.025)) < 1e-12);
  let threw = false;
  try { engine.coaxCapacitancePerMetre(2.3, 0.019, 0.008); } catch (e) { threw = e instanceof RangeError; }
  tryCheck('coax with inverted radii throws RangeError', () => threw);
  threw = false;
  try { engine.coaxCapacitancePerMetre(2.3, 0.02, 0.02); } catch (e) { threw = e instanceof RangeError; }
  tryCheck('coax with equal radii throws RangeError', () => threw);
  tryCheck('winner at the exact crossing is a tie', () =>
    engine.winnerAtDistance(100, 1, 400, 0.6, 750) === 'tie');
  tryCheck('winner just below the crossing is ac', () =>
    engine.winnerAtDistance(100, 1, 400, 0.6, 749) === 'ac');
  tryCheck('winner just above the crossing is dc', () =>
    engine.winnerAtDistance(100, 1, 400, 0.6, 751) === 'dc');
  tryCheck('zero frequency gives zero charging current', () =>
    engine.chargingCurrentPerMetre(2.5e-10, 127017.06, 0) === 0);
  tryCheck('zero ampacity gives zero L0', () =>
    engine.zeroDeliveryLengthMetres(0, 2.5e-10, 127017.06, 50) === 0);
}

// ── section 5: page coupling (reads the source tree only) ─────────────────

process.stdout.write(NL + '== 5. page coupling: the HTML ships constants this verifier can reproduce ==' + NL);

let html = '';
try {
  html = readFileSync(PAGE_PATH, 'utf8');
  check('page index.html exists and is readable', true);
} catch (err) {
  check('page index.html exists and is readable', false, String(err));
}

if (html) {
  tryCheck('page contains no em dash (U+2014) anywhere', () => !html.includes(String.fromCharCode(0x2014)));
  tryCheck('page ends with a real closing html tag', () => html.trimEnd().endsWith('</html>'));
  tryCheck('page links the site font stylesheet', () => html.includes('/fonts/fonts.css'));
  tryCheck('page prints the verifier command that exists', () =>
    html.includes('research/' + SLUG + '/verify-' + SLUG + '.mjs'));
  tryCheck('page meta description is filled in (no __DEK__ placeholder)', () =>
    !html.includes('<meta name="description" content="__DEK__" />'));
  tryCheck('page carries zero __DEK__ placeholders (meta, og, twitter, json-ld all filled)', () =>
    (html.split('__DEK__').length - 1) === 0);
  tryCheck('og/twitter titles use the middle-dot separator', () =>
    html.includes('The Crossing Where Direct Current Wins · Artificial Wasteland'));
  tryCheck('page loads no remote script', () => !html.includes('<script src="http'));

  // Every control the page script binds by id must exist in the markup with
  // that exact id. A missing id makes getElementById return null and the
  // first addEventListener call on it throws at load, killing the whole
  // instrument (this was the observed 390px script error: the markup used
  // id="uF" and id="iMax" while the script bound "uFPerKm" and "iMaxA").
  const bindIds = [];
  const bindRe = /bindRange\('([A-Za-z0-9_]+)'/g;
  let bindMatch;
  while ((bindMatch = bindRe.exec(html)) !== null) bindIds.push(bindMatch[1]);
  tryCheck('page binds its nine slider controls by id', () => bindIds.length >= 9);
  for (const id of bindIds) {
    tryCheck('page declares the bound control id "' + id + '"', () =>
      html.includes('id="' + id + '"'));
  }

  function block(re) {
    const m = html.match(re);
    return m ? m[1] : null;
  }
  function grabWithin(blockText, key) {
    if (blockText == null) return NaN;
    const m = blockText.match(new RegExp(key + ':\\s*([0-9.]+)'));
    return m ? Number(m[1]) : NaN;
  }
  const costBlock = block(/var COSTS = \{([^}]*)\}/);
  const seaBlock = block(/var SEA = \{([^}]*)\}/);
  tryCheck('page declares its COSTS constants block', () => costBlock != null);
  tryCheck('page declares its SEA constants block', () => seaBlock != null);

  if (costBlock != null && seaBlock != null) {
    const aAc = grabWithin(costBlock, 'aAc');
    const aDc = grabWithin(costBlock, 'aDc');
    const bAc = grabWithin(costBlock, 'bAc');
    const bDc = grabWithin(costBlock, 'bDc');
    const linkLen = grabWithin(costBlock, 'linkLen');
    const kvLL = grabWithin(seaBlock, 'kvLL');
    const uF = grabWithin(seaBlock, 'uFPerKm');
    const iMax = grabWithin(seaBlock, 'iMaxA');
    const hz = grabWithin(seaBlock, 'hz');
    const lenKm = grabWithin(seaBlock, 'lenKm');

    tryCheck('page default AC terminal cost is 100', () => aAc === 100);
    tryCheck('page default DC terminal cost is 400', () => aDc === 400);
    tryCheck('page default AC per-km cost is 1.00', () => bAc === 1);
    tryCheck('page default DC per-km cost is 0.60', () => bDc === 0.6);
    tryCheck('page default link length is 700 km', () => linkLen === 700);

    // Independent recomputation of the page's opening numbers, from the
    // extracted constants, by this verifier's own implementations.
    const dStar = localBreakEven(aAc, bAc, aDc, bDc);
    tryCheck('page defaults give the hand-checked crossing of 750 km', () =>
      dStar != null && Math.abs(dStar - 750) < 1e-9);
    tryCheck('page default link sits on the AC side of its own crossing', () =>
      localRootFind(aAc, bAc, aDc, bDc) != null && linkLen < dStar &&
      engine.winnerAtDistance(aAc, bAc, aDc, bDc, linkLen) === 'ac');

    const vPh = kvLL * 1000 / Math.sqrt(3);
    const cM = uF * 1e-6 / 1000;
    const l0 = localL0(iMax, cM, vPh, hz);
    // Hand-derived band: 220 kV, 0.25 uF/km, 800 A must land near 80 km,
    // comfortably inside 70 to 95. This is the order-of-magnitude anchor.
    tryCheck('page default L0 lands in the hand-derived 70 to 95 km band', () =>
      l0 / 1000 > 70 && l0 / 1000 < 95);
    // And the precise value, computed here from first principles.
    tryCheck('page default L0 matches independent computation (1e-9 rel)', () =>
      relDiff(l0, (iMax / (2 * Math.PI * hz * cM * vPh))) < 1e-9);
    tryCheck('page default cable length sits below its own L0', () =>
      lenKm * 1000 < l0);
    const icAtLen = localRate(cM, vPh, hz) * lenKm * 1000;
    tryCheck('page default charging current is a plausible fraction of ampacity', () =>
      icAtLen > 0 && icAtLen < iMax);
  }
}

// ── summary ───────────────────────────────────────────────────────────────

process.stdout.write(NL + '== summary ==' + NL);
const ran = passed + failed;
process.stdout.write('checks ran: ' + ran + NL);
process.stdout.write('checks passed: ' + passed + NL);
process.stdout.write('checks failed: ' + failed + NL);

let exitCode = 0;
if (ran === 0) {
  process.stdout.write('RESULT: ZERO CHECKS RAN, which is itself a failure.' + NL);
  exitCode = 1;
} else if (failed > 0) {
  process.stdout.write('RESULT: FAILURES PRESENT.' + NL);
  exitCode = 1;
} else {
  process.stdout.write('RESULT: ALL CHECKS PASS.' + NL);
}

// ── --mutate: prove the checks can fail ───────────────────────────────────
// Corrupt a TEMP COPY of engine.mjs (the original on disk is never touched),
// confirm the bytes actually changed, then confirm the check suite disagrees
// with local truth. If a corrupted engine still passes, exit non-zero.

if (process.argv.includes('--mutate')) {
  process.stdout.write(NL + '== mutation harness ==' + NL);
  const src = readFileSync(ENGINE_PATH, 'utf8');
  const MUTATIONS = [
    ['closed-form numerator', 'var dA = aDc - aAc;', 'var dA = aDc + aAc;'],
    ['power headroom sqrt removed', 'Math.sqrt(headroomSq)', 'headroomSq'],
    ['coax log argument widened', 'Math.log(rOuterM / rInnerM)', 'Math.log(rOuterM / rInnerM) + 1'],
    ['zero-delivery rate halved', 'return iMaxA / rate;', 'return iMaxA / (rate / 2);']
  ];

  let mutDir = null;
  let mutFailures = 0;
  try {
    mutDir = mkdtempSync(join(tmpdir(), 'aw-verify-mut-'));
    for (let i = 0; i < MUTATIONS.length; i++) {
      const [name, from, to] = MUTATIONS[i];
      const occurrences = src.split(from).length - 1;
      if (occurrences !== 1) {
        process.stdout.write('MUTATION SETUP ERROR: "' + name + '" target occurs ' +
          occurrences + ' times (expected exactly 1).' + NL);
        mutFailures++;
        continue;
      }
      const mutated = src.replace(from, to);
      if (mutated === src) {
        process.stdout.write('CORRUPTION DID NOT LAND for "' + name + '".' + NL);
        mutFailures++;
        continue;
      }
      const p = join(mutDir, 'engine-' + i + '.mjs');
      writeFileSync(p, mutated);
      const mod = await import(pathToFileURL(p).href + '?run=' + i);
      const bad = suiteAgainst(mod);
      if (bad > 0) {
        process.stdout.write('mutation "' + name + '": corruption landed, ' + bad +
          ' disagreement(s) detected. GOOD.' + NL);
      } else {
        process.stdout.write('mutation "' + name + '": checks STILL PASS on corrupted engine. BAD.' + NL);
        mutFailures++;
      }
    }
  } catch (err) {
    process.stdout.write('mutation harness error: ' + String(err) + NL);
    mutFailures++;
  } finally {
    if (mutDir) rmSync(mutDir, { recursive: true, force: true });
  }

  if (mutFailures > 0) {
    process.stdout.write('MUTATION RESULT: ' + mutFailures + ' problem(s); the checks are not trustworthy.' + NL);
    exitCode = 1;
  } else {
    process.stdout.write('MUTATION RESULT: every corruption was detected. The checks can fail.' + NL);
  }
}

process.exit(exitCode);

// ── compact suite used against mutated engines ────────────────────────────
// Counts disagreements between a candidate engine and this verifier's local
// truth. Runs the same comparisons as the anchors, on a smaller grid.

function suiteAgainst(E) {
  let bad = 0;
  const bes = [
    [100, 1, 400, 0.6],
    [50, 0.5, 300, 0.2],
    [200, 1.5, 600, 0.9],
    [100, 1, 250, 0.4],
    [100, 1, 400, 1]
  ];
  for (const [a, b, c, d] of bes) {
    const lt = localBreakEven(a, b, c, d);
    const gc = E.breakEvenClosedForm(a, b, c, d);
    const gb = E.breakEvenBisection(a, b, c, d);
    if ((lt == null) !== (gc.dStarKm == null)) bad++;
    else if (lt != null && relDiff(lt, gc.dStarKm) > 1e-9) bad++;
    if ((lt == null) !== (gb.dStarKm == null)) bad++;
    else if (lt != null && relDiff(lt, gb.dStarKm) > 1e-9) bad++;
  }
  const seas = [
    [800, 2.5e-10, 127017.06, 50],
    [500, 3.5e-10, 230940.11, 50],
    [1200, 1.5e-10, 38105.12, 60]
  ];
  for (const [im, cp, vp, hz] of seas) {
    const lt = localL0(im, cp, vp, hz);
    if (relDiff(lt, E.zeroDeliveryLengthMetres(im, cp, vp, hz)) > 1e-9) bad++;
    if (relDiff(lt, E.zeroDeliveryBisection(im, cp, vp, hz).lengthM) > 1e-9) bad++;
  }
  if (relDiff(localCoax(2.3, 0.008, 0.019), E.coaxCapacitancePerMetre(2.3, 0.008, 0.019)) > 1e-12) bad++;
  if (relDiff(localPower(800, 598.5, 127017.06), E.deliverablePowerWatts(800, 598.5, 127017.06)) > 1e-12) bad++;
  if (E.winnerAtDistance(100, 1, 400, 0.6, 750) !== 'tie') bad++;
  return bad;
}
