// verify.mjs — "It Was Never the Stuff" (P3 combine portal, 18th).
//
// Three independent guards:
//   (A) RE-DERIVE every operable number from the members' formulas FROM SCRATCH
//       (not by importing data.mjs's already-computed values).
//   (B) CROSS-CHECK the three members' own verifiers still pass (run them).
//   (C) DRIFT-GUARD: the built page carries the exact numbers, formulas, and
//       sources — so the reading can never silently drift from the ground.
//
//   node research/it-was-never-the-stuff/verify.mjs
//
// Exits non-zero on any failure.

'use strict';
import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DATA } from './data.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '../..');
const PAGE = join(ROOT, 'public/strata/it-was-never-the-stuff/index.html');

let pass = 0, fail = 0;
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
function ok(name, cond, got) {
  if (cond) { pass++; }
  else { fail++; console.error('  ✗ ' + name + (got !== undefined ? '  got: ' + got : '')); }
}

const D2R = Math.PI / 180;

// ════════════════════════ (A) RE-DERIVE FROM SCRATCH ════════════════════════
console.log('(A) re-derive every number from the members’ formulas');

// — KNIT — closed-loop bias geometry.
const eBias = (phi) => Math.SQRT2 * Math.cos((phi * D2R) / 2) - 1;
const phiJam = (dp) => Math.asin(dp) / D2R;
ok('bias on the grain: ε(90°) = 0', approx(eBias(90), 0, 1e-12), eBias(90));
ok('jam angle at d/p=0.5 is 30°', approx(phiJam(0.5), 30, 1e-9), phiJam(0.5));
ok('bias ε(30°) ≈ 0.36603', approx(eBias(phiJam(0.5)), 0.366025, 1e-5), eBias(30));
// yarn length ℓ = perimeter of the relaxed loop ellipse (a=5.0, c=3.8), fresh integral.
function ellipsePerim(a, c, N = 20000) {
  let L = 0, px = a, py = 0;
  for (let i = 1; i <= N; i++) {
    const t = (2 * Math.PI * i) / N, x = a * Math.cos(t), y = c * Math.sin(t);
    L += Math.hypot(x - px, y - py); px = x; py = y;
  }
  return L;
}
const L0 = ellipsePerim(5.0, 3.8);
ok('loop yarn length ℓ ≈ 27.78 mm', approx(L0, 27.78, 0.03), L0);
const S_MAX = L0 / (4 * 5.0) - 1;                 // idealised width strain at c→0
ok('knit width strain ≈ 0.389 at 0 yarn strain', approx(S_MAX, 0.389, 0.003), S_MAX);
ok('the ordering knit(~39%) ≈ bias(~37%) ≫ grain(4%)',
  S_MAX > eBias(30) && eBias(30) > 0.04 * 5 && 0.04 < eBias(30), [S_MAX, eBias(30)].join(','));

// — DENIM — ring-dyed cross-section.
const dyedArea = (dr) => { const core = Math.max(0, 1 - dr); return 1 - core * core; };
ok('dyed fraction at d/R=0.25 is exactly 0.4375 (43.8%)', approx(dyedArea(0.25), 0.4375, 1e-12), dyedArea(0.25));
ok('dyed fraction at d/R=0.20 is 0.36 (36.0%)', approx(dyedArea(0.20), 0.36, 1e-12), dyedArea(0.20));
ok('through-dyed d/R=1 is 1.0 (100%)', approx(dyedArea(1), 1.0, 1e-12), dyedArea(1));
// closed form == analytic annulus 1 − ((R−d)/R)²
const R = 7.3, d = 0.25 * R;
ok('closed form matches annulus areas', approx(dyedArea(d / R), 1 - Math.pow((R - d) / R, 2), 1e-12));
// fade curve: vat reaches pure white exactly at wear = d0 = 0.25.
const d0 = 0.25, vatBlue = (wr) => Math.max(0, Math.min(1, (d0 - wr) / d0));
ok('vat blue hits pure white at wear = d0', approx(vatBlue(0.25), 0, 1e-12), vatBlue(0.25));
ok('vat blue monotone non-increasing', vatBlue(0.10) > vatBlue(0.20) && vatBlue(0.20) > vatBlue(0.24));

// — CONTACT — Bowden–Tabor true area + splitting + JKR.
const A_APP = 1e-4, H_STEEL = 2.0e9, L_EX = 10;
const Areal = L_EX / H_STEEL, frac = Areal / A_APP;
ok('true area A=L/H = 5e-9 m² = 0.005 mm²', approx(Areal * 1e6, 0.005, 1e-6), Areal * 1e6);
ok('fraction touched = 0.005 %', approx(frac * 100, 0.005, 1e-6), frac * 100);
ok('doubling load doubles true area', approx((2 * L_EX / H_STEEL) / (L_EX / H_STEEL), 2, 1e-12));
const splitForce = (n) => Math.sqrt(n);
ok('contact splitting √100 = 10×', approx(splitForce(100), 10, 1e-12));
ok('contact splitting √1e6 = 1000×', approx(splitForce(1e6), 1000, 1e-9));
const jkr = (W, r) => 1.5 * Math.PI * W * r, dmt = (W, r) => 2 * Math.PI * W * r;
ok('JKR pull-off F=(3/2)πWR ≈ 1.178 mN', approx(jkr(0.05, 5e-3) * 1e3, 1.178, 0.001), jkr(0.05, 5e-3) * 1e3);
ok('JKR/DMT ratio 0.75, neither carries a modulus term', approx(jkr(1, 1) / dmt(1, 1), 0.75, 1e-12));

// — the data.mjs source of truth agrees with these fresh derivations —
const K = DATA.movements.find((m) => m.id === 'knit');
const Dn = DATA.movements.find((m) => m.id === 'denim');
const Cn = DATA.movements.find((m) => m.id === 'contact');
ok('data.mjs knit% matches fresh derivation', approx(K.knitStrainPct, +(S_MAX * 100).toFixed(1), 0.05), K.knitStrainPct);
ok('data.mjs denim rep% matches', approx(Dn.repDyedPct, 43.8, 0.05), Dn.repDyedPct);
ok('data.mjs contact frac% matches', approx(Cn.exFracPct, 0.005, 1e-6), Cn.exFracPct);
ok('the reading sorts 2 gated + 1 constituted',
  DATA.synthesis.filter((s) => s.depth === 'gated').length === 2 &&
  DATA.synthesis.filter((s) => s.depth === 'constituted').length === 1);

// ════════════════════════ (B) CROSS-CHECK THE MEMBERS ════════════════════════
console.log('(B) the three members’ own verifiers still pass');
const members = [
  ['why-knitting-stretches', 'research/why-knitting-stretches/verify.mjs'],
  ['why-denim-fades', 'research/why-denim-fades/verify-why-denim-fades.mjs'],
  ['real-area-of-contact', 'research/real-area-of-contact/verify.mjs'],
];
for (const [name, rel] of members) {
  let good = true;
  try { execFileSync('node', [join(ROOT, rel)], { cwd: ROOT, stdio: 'pipe' }); }
  catch { good = false; }
  ok('member verifier passes: ' + name, good);
}

// ════════════════════════ (C) DRIFT-GUARD THE BUILT PAGE ════════════════════════
console.log('(C) the built page carries the exact numbers, formulas, and sources');
let html = '';
try { html = readFileSync(PAGE, 'utf8'); } catch { }
ok('built page exists', html.length > 1000);
const need = [
  // knit
  'ε(φ) = √2·cos(φ/2) − 1', '0.0%', K.knitStrainPct + '%', K.biasStrainPct + '%',
  'arxiv.org/abs/1801.08355', 'Poincloux', 'no elastane', 'on the grain',
  // denim
  'f = 1 − (1 − d/R)²', '43.8%', '100', 'ring-dyed', 'vat dye', 'covalent',
  // contact
  'A_real = L / H', '0.005 mm²', '0.005%', 'Bowden', 'Arzt', 'Johnson', '√n',
  // the reading + chrome
  'shape-gated', 'shape-constituted', 'What survives', 'home-banner.js',
  'https://artwaste.land/strata/it-was-never-the-stuff/', '2026-07-15',
  // members walked
  'why-knitting-stretches', 'why-denim-fades', 'real-area-of-contact',
];
for (const s of need) ok('page carries: ' + JSON.stringify(s), html.includes(s));
// the embedded JSON round-trips
const m = html.match(/<script id="portal-data" type="application\/json">([\s\S]*?)<\/script>/);
ok('portal-data JSON is present + parses', !!m && (() => { try { JSON.parse(m[1].replace(/\\u003c/g, '<')); return true; } catch { return false; } })());

// ════════════════════════ REPORT ════════════════════════
const total = pass + fail;
console.log('\n' + (fail === 0 ? '✓' : '✗') + ' ' + pass + '/' + total + ' checks pass');
if (fail > 0) { console.error(fail + ' FAILED'); process.exit(1); }
