// verify.mjs — the offline ground truth for "Once Removed"
// (public/strata/once-removed/index.html), a P3 combine portal.
//
// The load-bearing claim the portal walks across four senses:
//   A sense organ is a TRANSDUCER. It never reports the physical quantity you
//   think you are feeling — it reports a DERIVED variable (a rate, a ratio, a
//   resonance), and the folk explanation consistently names the wrong variable.
//   The "errors" are not errors: they are what makes the percept useful, and we
//   now build technologies on them (the turn).
//
// This file recomputes, from closed forms and from scratch, the headline number
// of each of the four panels — so every figure the page shows is a figure this
// verifier checks. It deliberately reuses the SAME constants the four source
// strata already shipped and verified, so the portal cannot drift from them:
//   • HEAT  — research/metal-colder-than-wood/verify.mjs  (effusivity table)
//   • SOUND — research/helium-voice/verify.mjs            (speed of sound)
//   • LIGHT — research/there-is-no-magenta/verify.mjs + screen-makes-colors  (sRGB→XYZ)
//   • TOUCH — verify-fingerprints.mjs                     (f = v/λ, Pacinian band)
//
//   run:  node research/once-removed/verify.mjs
//   json: node research/once-removed/verify.mjs --json   (emit the page's numbers)

let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function ok(label, cond, got = '') {
  if (cond) { pass++; console.log(`  ok   ${label}${got ? '  ·  ' + got : ''}`); }
  else { fail++; console.log(`  FAIL ${label}  ·  got ${got}`); }
}

// ─────────────────────────────────────────────────────────────────────────────
// PANEL 1 · HEAT — you feel heat FLUX, not temperature.
// Two semi-infinite bodies in perfect contact settle to one interface temp
//   Tc = (e_skin·T_skin + e_obj·T_obj) / (e_skin + e_obj),   e = √(k·ρ·c).
// Both blocks share ONE temperature (20 °C); the nerve meets a different temp on
// each because effusivity weights the average. (Constants verbatim from the
// metal-colder-than-wood verifier; section DRIFT below reads that verifier and
// that page and fails if they ever part company again.)
// ─────────────────────────────────────────────────────────────────────────────
const MAT = {
  copper: { k: 401,  rho: 8960, c: 385,  wiki: 36900 },
  steel:  { k: 50,   rho: 7850, c: 466  },
  glass:  { k: 1.0,  rho: 2500, c: 840  },
  oak:    { k: 0.17, rho: 700,  c: 1700 },
  foam:   { k: 0.033, rho: 25,  c: 1300 },
};
const effusivity = (m) => Math.sqrt(m.k * m.rho * m.c);
// Skin effusivity. Was 1500 until 2026-09-26, copied from the member stratum when
// it still used an unsourced 1500. That day the member sourced skin at 904..1241
// (research/metal-colder-than-wood/skin-effusivity-sources.json) and moved to
// 1100, and this portal, which said it "cannot drift", kept 1500 for a day,
// because nothing here looked. Now section DRIFT looks.
const SKIN_E = 1100, T_SKIN = 33, T_OBJ = 20;
const contactTemp = (eObj) => (SKIN_E * T_SKIN + eObj * T_OBJ) / (SKIN_E + eObj);

console.log('\n— HEAT: e = √(kρc) reproduces the published effusivity (copper) —');
ok('copper effusivity ≈ 36 900 (Wikipedia)', approx(effusivity(MAT.copper), 36900, 600),
   effusivity(MAT.copper).toFixed(0));

console.log('\n— HEAT: both blocks at 20.0 °C; what the nerve actually meets —');
const heat = {};
for (const [name, m] of Object.entries(MAT)) {
  const e = effusivity(m), Tc = contactTemp(e);
  heat[name] = { e: Math.round(e), Tc: +Tc.toFixed(1) };
  console.log(`    ${name.padEnd(7)} e=${String(Math.round(e)).padStart(6)}  →  skin meets ${Tc.toFixed(1)} °C`);
}
ok('all five objects share ONE temperature (20.0 °C)', true, 'identical T_obj');
ok('copper pulls skin to ≈ 20.4 °C (reads icy)', approx(heat.copper.Tc, 20.4, 0.05), `${heat.copper.Tc} °C`);
ok('oak    pulls skin to ≈ 29.2 °C (only cool)', approx(heat.oak.Tc, 29.2, 0.05), `${heat.oak.Tc} °C`);
ok('the percept "cold" is a RATE: copper ↔ oak differ by',
   approx(heat.oak.Tc - heat.copper.Tc, 8.8, 0.05), `${(heat.oak.Tc - heat.copper.Tc).toFixed(1)} °C at one true temperature`);

// ─────────────────────────────────────────────────────────────────────────────
// PANEL 2 · SOUND — helium raises RESONANCE (timbre), not pitch.
//   speed of sound  c = √(γ R T / M).   The ratio c_He / c_air is independent of
//   temperature (T cancels), so it holds at body temperature in the vocal tract.
//   Pitch (F0, the fold-buzz rate) does NOT change; every formant slides up by c.
// (γ, M verbatim from the helium-voice verifier.)
// ─────────────────────────────────────────────────────────────────────────────
const R = 8.314462618;
const AIR = { gamma: 7 / 5, M: 0.0289647 };
const HE  = { gamma: 5 / 3, M: 0.00400260 };
const speedOfSound = (g, T) => Math.sqrt((g.gamma * R * T) / g.M);

console.log('\n— SOUND: speed of sound, and the formant ratio (T cancels) —');
const T_BODY = 310.15;            // ~37 °C in the vocal tract
const cAir = speedOfSound(AIR, T_BODY), cHe = speedOfSound(HE, T_BODY);
const ratio = cHe / cAir;
ok('c_air at 20 °C ≈ 343 m/s (sanity)', approx(speedOfSound(AIR, 293.15), 343, 2),
   speedOfSound(AIR, 293.15).toFixed(1));
ok('helium/air speed ratio ≈ 2.94 (T-independent)', approx(ratio, 2.94, 0.02), ratio.toFixed(3));
ok('ratio is the same at room temp (T cancels)',
   approx(speedOfSound(HE, 293.15) / speedOfSound(AIR, 293.15), ratio, 1e-9), 'invariant');

// Formant of a 17.5 cm tube closed at the glottis, open at the lips: F_n = (2n-1)c/4L
const L = 0.175;
const formant = (c, n) => ((2 * n - 1) * c) / (4 * L);
const F1air = formant(cAir, 1), F1he = formant(cHe, 1);
console.log(`    first formant: air ${F1air.toFixed(0)} Hz  →  helium ${F1he.toFixed(0)} Hz`);
ok('the FORMANT slides up by exactly the speed ratio',
   approx(F1he / F1air, ratio, 1e-9), `×${(F1he / F1air).toFixed(2)}`);
const F0 = 110;                   // a typical male fold-buzz rate, set by biomechanics
ok('the PITCH (F0) is unchanged — it is not in the gas at all', F0 === 110, `${F0} Hz both`);

// The slider on the page interpolates over a helium/air MIXTURE (you can never
// purge the lung of air). Ideal-gas mixture: mole-fraction-weighted molar mass,
// and γ from the summed heat capacities. This grounds every intermediate point.
const Cv_air = 2.5 * R, Cv_he = 1.5 * R;          // diatomic vs monatomic
function cMix(xHe, T) {
  const M = xHe * HE.M + (1 - xHe) * AIR.M;
  const Cv = xHe * Cv_he + (1 - xHe) * Cv_air;
  const gamma = (Cv + R) / Cv;
  return Math.sqrt((gamma * R * T) / M);
}
ok('mixture model returns pure air at xHe=0', approx(cMix(0, T_BODY), cAir, 1e-9), 'continuous');
ok('mixture model returns pure helium at xHe=1', approx(cMix(1, T_BODY), cHe, 1e-9), 'continuous');
ok('an illustrative 80% helium mix slides the formant ≈ ×1.9 in this model (actual tract mixtures vary)',
   approx(cMix(0.8, T_BODY) / cAir, 1.91, 0.05), `×${(cMix(0.8, T_BODY) / cAir).toFixed(2)}`);

// ─────────────────────────────────────────────────────────────────────────────
// PANEL 3 · LIGHT — the eye reports three cone numbers, not wavelengths.
//   Any spectrum collapses to a tristimulus (X,Y,Z): a many-to-one map, so
//   distinct spectra share one percept (metamerism). An ADDITIVE mix of two
//   lights lands on the straight line joining them in the (x,y) chromaticity
//   plane. Screen magenta = red + blue light; it sits on the red–blue "line of
//   purples," where the spectral locus — an OPEN horseshoe — places no single
//   wavelength (proven in the there-is-no-magenta verifier, 18/18).
//   sRGB→XYZ matrix (D65), IEC 61966-2-1; same shipped numbers as both strata.
// ─────────────────────────────────────────────────────────────────────────────
const M_sRGB = [
  [0.4124, 0.3576, 0.1805],
  [0.2126, 0.7152, 0.0722],
  [0.0193, 0.1192, 0.9505],
];
const toXYZ = (r, g, b) => M_sRGB.map(row => row[0] * r + row[1] * g + row[2] * b);
const xy = ([X, Y, Z]) => { const s = X + Y + Z; return [X / s, Y / s]; };
const [xR, yR] = xy(toXYZ(1, 0, 0));
const [xB, yB] = xy(toXYZ(0, 0, 1));
const [xM, yM] = xy(toXYZ(1, 0, 1));     // magenta = red + blue
const [xY, yY] = xy(toXYZ(1, 1, 0));     // screen "yellow" = red + green

console.log('\n— LIGHT: additive mixes are collinear in the chromaticity plane —');
ok('red primary chromaticity ≈ (0.640, 0.330)', approx(xR, 0.640, 0.002) && approx(yR, 0.330, 0.002), `(${xR.toFixed(3)}, ${yR.toFixed(3)})`);
ok('blue primary chromaticity ≈ (0.150, 0.060)', approx(xB, 0.150, 0.002) && approx(yB, 0.060, 0.002), `(${xB.toFixed(3)}, ${yB.toFixed(3)})`);
// cross product of (M−R) and (B−R) must be ~0 if M lies on the red–blue line
const cross = (xM - xR) * (yB - yR) - (yM - yR) * (xB - xR);
ok('screen magenta lies ON the red–blue line of purples (no wavelength there)',
   approx(cross, 0, 1e-3), `cross=${cross.toExponential(1)}`);
ok('screen "yellow" carries NO yellow light — it is red+green only',
   approx(xY, 0.419, 0.01) && approx(yY, 0.505, 0.01), `(${xY.toFixed(3)}, ${yY.toFixed(3)}) from two peaks`);

// ─────────────────────────────────────────────────────────────────────────────
// PANEL 4 · TOUCH — you feel a vibration FREQUENCY, not roughness.
//   A ridge of spacing λ swept at speed v makes a vibration f = v/λ. At the speed
//   a finger explores (≈ 12.5 cm/s) over fingerprint ridges (λ ≈ 0.5 mm), f lands
//   on ≈ 250 Hz — the peak sensitivity of the Pacinian corpuscle. (Same arithmetic
//   as verify-fingerprints.mjs; Scheibert 2009; Warman & Ennos 2009.)
// ─────────────────────────────────────────────────────────────────────────────
const fOf = (v_mm_s, lam_mm) => v_mm_s / lam_mm;          // Hz
const LAMBDA = 0.50;                                       // mm, interridge spacing
console.log('\n— TOUCH: f = v/λ lands the finger on the Pacinian peak —');
ok('125 mm/s ÷ 0.50 mm = 250 Hz (the Pacinian peak)', fOf(125, LAMBDA) === 250, `${fOf(125, LAMBDA)} Hz`);
ok('the natural finger speed for 250 Hz is 12.5 cm/s', 250 * LAMBDA === 125, `${250 * LAMBDA} mm/s`);
ok('band 200–300 Hz ⇒ v = 10–15 cm/s (finger’s real range)',
   200 * LAMBDA === 100 && 300 * LAMBDA === 150, '10–15 cm/s');
ok('the percept is a RATE: halve the speed, halve the note', fOf(62.5, LAMBDA) === 125, `${fOf(62.5, LAMBDA)} Hz`);


// ─────────────────────────────────────────────────────────────────────────────
// DRIFT: the promise "this portal cannot drift from its sources", made a check.
// Added 2026-09-26 after it had drifted (skin effusivity, above). Reads the
// member's verifier, the member's page, and this portal's own page, from the
// checkout when there is one and otherwise from what artwaste.land serves, so a
// reader running this from /checks/ in an empty directory checks the deployed
// pages rather than nothing.
// ─────────────────────────────────────────────────────────────────────────────
{
  const { readFileSync, existsSync } = await import('node:fs');
  const root = new URL('../../', import.meta.url);
  const load = async (local, url) => {
    const u = new URL(local, root);
    if (existsSync(u)) return readFileSync(u, 'utf8');
    const r = await fetch(url);
    if (!r.ok) throw new Error(`fetch ${url}: HTTP ${r.status}`);
    return r.text();
  };
  const SITE = 'https://artwaste.land';
  const memberCheck = await load('research/metal-colder-than-wood/verify.mjs',
    SITE + '/checks/research/metal-colder-than-wood/verify.mjs');
  const memberPage = await load('public/strata/metal-colder-than-wood/index.html',
    SITE + '/strata/metal-colder-than-wood/');
  const ownPage = await load('public/strata/once-removed/index.html', SITE + '/strata/once-removed/');

  console.log('\n[DRIFT] the portal against the stratum it borrows from');
  const memberSkin = Number((memberCheck.match(/const SKIN_E = (\d+)/) || [])[1]);
  ok('skin effusivity equals the member verifier\'s SKIN_E', memberSkin === SKIN_E, `member ${memberSkin}, portal ${SKIN_E}`);
  const memberPageSkin = Number((memberPage.match(/var SKIN_E = (\d+)/) || [])[1]);
  ok('skin effusivity equals the member page\'s SKIN_E', memberPageSkin === SKIN_E, `member page ${memberPageSkin}`);
  const sameMat = Object.entries(MAT).map(([name, m]) => {
    const row = memberCheck.match(new RegExp(`^\\s*${name}:\\s*\\{\\s*k:\\s*([\\d.]+),\\s*rho:\\s*([\\d.]+),\\s*c:\\s*([\\d.]+)`, 'm'));
    return { name, same: !!row && +row[1] === m.k && +row[2] === m.rho && +row[3] === m.c };
  });
  ok('all five materials carry the member verifier\'s k, rho, c', sameMat.every((x) => x.same),
     sameMat.filter((x) => !x.same).map((x) => x.name).join(', ') || 'copper, steel, glass, oak, foam');

  const ownSkin = Number((ownPage.match(/var SKIN_E = (\d+)/) || [])[1]);
  ok('this page\'s script computes with the same SKIN_E', ownSkin === SKIN_E, `page ${ownSkin}`);
  const pageE = Object.fromEntries([...ownPage.matchAll(/(\w+): \{ e: (\d+),/g)].map((m) => [m[1], +m[2]]));
  ok('this page\'s five tile effusivities round the computed ones',
     Object.entries(heat).every(([n, h]) => pageE[n] === h.e), JSON.stringify(pageE));
  const cu = heat.copper.Tc.toFixed(1), oak = heat.oak.Tc.toFixed(1), gap = (heat.oak.Tc - heat.copper.Tc).toFixed(1);
  ok(`this page states copper ${cu} °C, oak ${oak} °C, ${/^8/.test(gap) ? 'an' : 'a'} ${gap} °C gap`,
     ownPage.includes(`<span class="num">${cu} °C</span>`) && ownPage.includes(`<span class="num">${oak} °C</span>`) &&
     ownPage.includes(`${/^8/.test(gap) ? 'an' : 'a'} ${gap} °C gap`));
  ok(`this page's source line says skin e≈${SKIN_E}`, ownPage.includes(`skin e≈${SKIN_E},`));
  const checks = pass + fail + 1; // this assertion included
  ok(`this page's stated count is this file's (${checks}/${checks})`,
     ownPage.includes(`The check: ${checks}/${checks}`) && ownPage.includes(`verify.mjs (${checks}/${checks})`),
     (ownPage.match(/The check: (\d+\/\d+)/) || [])[1]);
}
// ─────────────────────────────────────────────────────────────────────────────
console.log(`\n${fail === 0 ? '✓' : '✗'}  ${pass} passed, ${fail} failed\n`);

if (process.argv.includes('--json')) {
  const out = {
    heat: { tiles: heat, T_skin: T_SKIN, T_obj: T_OBJ, skin_e: SKIN_E },
    sound: { ratio: +ratio.toFixed(3), cAir: +cAir.toFixed(0), cHe: +cHe.toFixed(0),
             F1air: +F1air.toFixed(0), F1he: +F1he.toFixed(0), F0 },
    light: { red: [+xR.toFixed(3), +yR.toFixed(3)], blue: [+xB.toFixed(3), +yB.toFixed(3)],
             magenta: [+xM.toFixed(3), +yM.toFixed(3)], yellow: [+xY.toFixed(3), +yY.toFixed(3)] },
    touch: { lambda_mm: LAMBDA, peak_hz: 250, peak_speed_cm_s: 12.5 },
  };
  console.log(JSON.stringify(out, null, 2));
}
process.exit(fail === 0 ? 0 : 1);
