// verify.mjs — the physics behind the stratum
// "The Cold That Isn't There" (/strata/metal-colder-than-wood/).
//
// The claim the page corrects: a metal spoon and a wooden one, sitting in the
// same room, are at the SAME temperature — yet the metal feels colder. Nothing
// about the metal is cold. What differs is how fast each material drains heat
// from the warm skin that touches it. The governing property is THERMAL
// EFFUSIVITY, e = sqrt(k·rho·c), and the temperature your nerves actually meet
// at the contact surface is the effusivity-weighted average
//
//        T_contact = (e_skin·T_skin + e_obj·T_obj) / (e_skin + e_obj).
//
// What this script proves, offline and from scratch:
//   1. e = sqrt(k·rho·c) computed from sourced (k, rho, c) triples reproduces
//      Wikipedia's directly-published effusivity table to within property-value
//      scatter (copper, aluminium, iron, water, concrete) — the page's numbers
//      are not asserted, they fall out of textbook material properties.
//   2. The contact-temperature formula is the exact interface value for two
//      semi-infinite bodies in perfect contact, and it is CONSTANT in time
//      (independent of t) — verified against the exact error-function solution
//      of the 1-D heat equation that the page animates.
//   3. The headline result: with every object at 20 C and skin at 33 C, the
//      contact temperature ranges from ~20.4 C (copper) to ~32.6 C (foam),
//      while the objects' own temperatures are identical. That spread is the
//      whole sensation.
//   4. The reversal: push the object ABOVE skin temperature (a 50 C sauna) and
//      the SAME high-effusivity metal now feels HOTTER than wood — confirming
//      the effect is heat-flow rate, not a "cold material."
//   5. Cold receptors (TRPM8) begin firing as skin cools past ~26-31.7 C, so the
//      contact temperatures sort cleanly into "reads cold" vs "reads neutral".
//   6. (added 2026-09-26) Skin's own effusivity: recompute it from every source
//      recorded in skin-effusivity-sources.json (verbatim excerpts + URLs), check
//      the range the page states matches their span, and check that the page's
//      verdicts survive at both ends of that span.
//
//   run:  node research/metal-colder-than-wood/verify.mjs
//
// No dependencies. Every number the page displays is recomputed here.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── Material properties (SI), each a sourced triple ─────────────────────────
//   k    = thermal conductivity        W/(m·K)
//   rho  = density                     kg/m^3
//   c    = specific heat capacity      J/(kg·K)
// Values are standard textbook/handbook figures (CRC, Engineering ToolBox,
// Incropera). Real materials scatter — alloy, species, grain, moisture — so
// these are representative, and the page names the spread. The QUALITATIVE
// ordering (metal >> glass > wood > foam) is robust to any reasonable choice.
const MAT = {
  copper:    { k: 401,   rho: 8960, c: 385,  wiki: 36900 },
  aluminium: { k: 237,   rho: 2700, c: 897,  wiki: 23700 },
  iron:      { k: 80.2,  rho: 7870, c: 449,  wiki: 15900 },
  water:     { k: 0.606, rho: 998,  c: 4180, wiki: 1600  },
  concrete:  { k: 1.8,   rho: 2400, c: 880,  wiki: 2000  }, // dense concrete (the most variable here)
  // touch tiles (no single published effusivity to cross-check, computed here):
  steel:     { k: 50,    rho: 7850, c: 466 },   // mild/structural steel — the everyday "metal"
  glass:     { k: 1.0,   rho: 2500, c: 840 },
  oak:       { k: 0.17,  rho: 700,  c: 1700 },  // oak across the grain
  foam:      { k: 0.033, rho: 25,   c: 1300 },  // expanded polystyrene
};

const effusivity = (m) => Math.sqrt(m.k * m.rho * m.c);
const diffusivity = (m) => m.k / (m.rho * m.c); // alpha = k/(rho·c)

// ── 1. Computed effusivity reproduces Wikipedia's published table ───────────
console.log('\n— effusivity e = sqrt(k·rho·c) vs published values —');
for (const [name, m] of Object.entries(MAT)) {
  const e = effusivity(m);
  if (m.wiki) {
    // within ~12% — property handbooks differ on which k/c they tabulate
    const rel = Math.abs(e - m.wiki) / m.wiki;
    ok(`${name.padEnd(10)} e≈${Math.round(e)}  (wiki ${m.wiki})`, rel < 0.12,
       `Δ=${(100 * rel).toFixed(1)}%`);
  } else {
    console.log(`  ··  ${name.padEnd(10)} e≈${Math.round(e)}`);
  }
}

// ── The contact-temperature formula ─────────────────────────────────────────
// Two semi-infinite bodies, skin (effusivity e1, temp T1) and object (e2, T2),
// brought into perfect contact. The interface temperature is
//   Tc = (e1·T1 + e2·T2) / (e1 + e2)
const SKIN_E = 1100;   // midpoint of the sourced skin span 904..1241, 2 s.f. (section 6); was 1500 until 2026-09-26
const contactTemp = (eSkin, Tskin, eObj, Tobj) =>
  (eSkin * Tskin + eObj * Tobj) / (eSkin + eObj);

// ── 2. The formula is the EXACT interface value of the heat equation, ∀t ─────
// For two semi-infinite solids in contact, the exact temperature field is
//   object side (x>0):  T = Tc + (Tobj - Tc)·erf( x / (2·sqrt(alpha2·t)) )
//   skin   side (x<0):  T = Tc + (Tskin - Tc)·erf(|x| / (2·sqrt(alpha1·t)) )
// At the interface x=0, erf(0)=0, so T(0,t) = Tc for ALL t. Check that the heat
// FLUX matches across the interface (the condition that fixes Tc): the flux into
// each side must be equal and opposite at x=0.
function erf(x) { // Abramowitz & Stegun 7.1.26, |error| < 1.5e-7
  const t = 1 / (1 + 0.3275911 * Math.abs(x));
  const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t
                  - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
  return x < 0 ? -y : y;
}
// flux q = -k dT/dx; for the erf profile, |q(0,t)| = e·|T_surface - Tc| / sqrt(pi·t)
// (because d/dx erf(x/(2√(αt))) at 0 = 1/sqrt(pi·alpha·t) and k/sqrt(alpha)=e).
console.log('\n— Tc is the unique interface temp balancing the heat flux —');
{
  const skin = { k: 0.4, rho: 1100, c: 3500 }; // a skin-like solid, e≈1244
  for (const name of ['steel', 'oak']) {
    const obj = MAT[name];
    const e1 = effusivity(skin), e2 = effusivity(obj);
    const T1 = 33, T2 = 20;
    const Tc = contactTemp(e1, T1, e2, T2);
    // flux out of skin into interface vs flux into object — must be equal:
    const t = 5; // any time; the ratio is t-independent
    const qSkin = e1 * (T1 - Tc) / Math.sqrt(Math.PI * t); // skin loses heat
    const qObj  = e2 * (Tc - T2) / Math.sqrt(Math.PI * t); // object gains heat
    ok(`${name.padEnd(6)} flux balance  q_skin=${qSkin.toFixed(2)} q_obj=${qObj.toFixed(2)}`,
       approx(qSkin, qObj, 1e-6), `Tc=${Tc.toFixed(2)}°C`);
  }
  // interface really is t-independent: erf(0)=0 exactly
  ok('interface temp independent of time (erf(0)=0)', approx(erf(0), 0, 1e-6), `erf(0)=${erf(0).toExponential(1)}`);
}

// ── 3. Headline: same object temp, wildly different contact temp ────────────
console.log('\n— every object at 20.0°C, skin at 33.0°C — what the nerve meets —');
const Tobj = 20, Tskin = 33;
const tiles = ['copper', 'steel', 'glass', 'oak', 'foam'];
const rows = tiles.map((name) => {
  const e = effusivity(MAT[name]);
  const Tc = contactTemp(SKIN_E, Tskin, e, Tobj);
  return { name, e, Tc };
});
for (const r of rows) {
  console.log(`  ${r.name.padEnd(7)} e≈${String(Math.round(r.e)).padStart(5)}  ` +
              `object=20.0°C  →  skin meets ${r.Tc.toFixed(1)}°C`);
}
// the objects are identical in temperature; the contact temps are not
ok('all objects share one temperature (20.0°C)', tiles.every(() => true));
ok('copper pulls skin coldest, foam barely cools it',
   rows[0].Tc < rows[4].Tc - 10, `Δ=${(rows[4].Tc - rows[0].Tc).toFixed(1)}°C spread`);
ok('contact temp is monotone in effusivity (higher e → colder)',
   rows.every((r, i) => i === 0 || r.Tc > rows[i - 1].Tc));
// pinned reference values (so a regression in the formula is caught):
ok('copper contact ≈ 20.4°C', approx(rows[0].Tc, 20.37, 0.05), `${rows[0].Tc.toFixed(2)}`);
ok('oak    contact ≈ 29.2°C', approx(rows[3].Tc, 29.23, 0.05), `${rows[3].Tc.toFixed(2)}`);
ok('foam   contact ≈ 32.6°C', approx(rows[4].Tc, 32.62, 0.05), `${rows[4].Tc.toFixed(2)}`);

// ── 4. The reversal: object hotter than skin → metal feels HOTTER ───────────
console.log('\n— the reversal: a 50°C bench, skin still 33°C —');
{
  const Th = 50;
  const cuTc  = contactTemp(SKIN_E, Tskin, effusivity(MAT.copper), Th);
  const oakTc = contactTemp(SKIN_E, Tskin, effusivity(MAT.oak),    Th);
  console.log(`  copper → skin meets ${cuTc.toFixed(1)}°C (burns);  oak → ${oakTc.toFixed(1)}°C (mild)`);
  ok('above skin temp, copper now delivers MORE heat than oak (feels hotter)',
     cuTc > oakTc + 10, `Δ=${(cuTc - oakTc).toFixed(1)}°C`);
  ok('at object = skin temp, contact temp = skin temp for EVERY material (no sensation)',
     tiles.every((n) => approx(contactTemp(SKIN_E, 33, effusivity(MAT[n]), 33), 33, 1e-9)));
}

// ── 5. Cold receptors sort the contact temps into cold vs neutral ───────────
// TRPM8 cold thermoreceptors begin firing as skin cools below ~26–31.7°C
// (heterologous threshold ~26°C; low-threshold cutaneous thermoreceptors ~31.7°C).
console.log('\n— TRPM8 cold-receptor threshold band 26–31.7°C —');
{
  const reads = (Tc) => Tc < 26 ? 'COLD' : Tc < 31.7 ? 'cool' : 'neutral';
  for (const r of rows) console.log(`  ${r.name.padEnd(7)} ${r.Tc.toFixed(1)}°C → reads ${reads(r.Tc)}`);
  ok('copper/steel/glass read cold/cool; foam reads neutral',
     reads(rows[0].Tc) === 'COLD' && reads(rows[4].Tc) === 'neutral');
}

// ── 6. Skin effusivity: sourced range, stated range, and sensitivity ───────
// Added 2026-09-26. The page used to say "literature spans ~1000–1700" with no
// source. skin-effusivity-sources.json records what we could fetch; e is
// recomputed here from the raw inputs each source prints.
console.log('\n[skin effusivity: recorded sources vs the range the page states]');
{
  // Read from the checkout when there is one; a reader running this from /checks/ in an
  // empty directory has neither file, so fetch the copies the site serves beside the page
  // (the sources JSON is published there byte for byte). The markdown source is not served,
  // so its assertions live in verify-surface.mjs, which only the repository runs.
  const { readFileSync, existsSync } = await import('node:fs');
  const here = new URL('.', import.meta.url);
  const root = new URL('../../', here);
  const SITE = 'https://artwaste.land/strata/metal-colder-than-wood/';
  const load = async (local, served) => {
    const u = new URL(local, root);
    if (existsSync(u)) return readFileSync(u, 'utf8');
    const r = await fetch(SITE + served);
    if (!r.ok) throw new Error(`fetch ${SITE + served}: HTTP ${r.status}`);
    return r.text();
  };
  const src = JSON.parse(await load('research/metal-colder-than-wood/skin-effusivity-sources.json', 'skin-effusivity-sources.json')).sources;
  const vals = [];
  for (const x of src) {
    if (x.inputs) {
      const i = x.inputs;
      const e = i.rhoc ? Math.sqrt(i.k * i.rhoc) : Math.sqrt(i.k * i.rho * i.c);
      vals.push(e);
      if (x.published_e != null)
        ok(`${x.id.padEnd(17)} e=${e.toFixed(0)} matches the printed ${x.published_e}`,
           Math.abs(e - x.published_e) / x.published_e < 0.01);
      else console.log(`  ··  ${x.id.padEnd(17)} e=${e.toFixed(0)} (computed; source prints k, rho, c only)`);
    } else {
      const i = x.inputs_envelope; // e = k / sqrt(alpha)
      const lo = i.k_lo / Math.sqrt(i.alpha_hi), hi = i.k_hi / Math.sqrt(i.alpha_lo);
      vals.push(lo, hi);
      console.log(`  ··  ${x.id.padEnd(17)} e in [${lo.toFixed(0)}, ${hi.toFixed(0)}] (envelope of k and alpha ranges)`);
    }
  }
  const sMin = Math.min(...vals), sMax = Math.max(...vals);
  const lo50 = Math.floor(sMin / 50) * 50, hi50 = Math.ceil(sMax / 50) * 50;
  ok(`sources span ${sMin.toFixed(0)}..${sMax.toFixed(0)}, i.e. about ${lo50} to ${hi50}`, sources_ok(src), `${src.length} sources`);
  function sources_ok(a) { return a.length >= 3 && a.every((x) => /^https:\/\//.test(x.url) && x.excerpt && x.excerpt.length > 40); }

  // What the page says. Numbers may be written 1250, 1 250 or 1&thinsp;250.
  const num = (t) => Number(t.replace(/&thinsp;|\s/g, ''));
  const RANGE = /about (?:<span class="mono">)?(\d(?:&thinsp;| )?\d{3}|\d{3})(?:<\/span>)? (?:and|to) (?:<span class="mono">)?(\d(?:&thinsp;| )?\d{3}|\d{3})(?:<\/span>)?/g;
  const files = {
    html: await load('public/strata/metal-colder-than-wood/index.html', ''),
  };
  for (const [name, text] of Object.entries(files)) {
    const found = [...text.matchAll(RANGE)].map((m) => ({
      lo: num(m[1]), hi: num(m[2]),
      old: /used to say[^.]*$/.test(text.slice(Math.max(0, m.index - 160), m.index)),
    }));
    const current = found.filter((f) => !f.old);
    ok(`${name}: every skin range it states now is ${lo50} to ${hi50}`,
       current.length >= 2 && current.every((f) => f.lo === lo50 && f.hi === hi50),
       current.map((f) => `${f.lo}-${f.hi}`).join(', '));
    ok(`${name}: the unsourced "~1000–1700" wording is gone`, !/1000\s*[–-]\s*1700/.test(text));
  }
  const pageSkinE = Number((files.html.match(/var SKIN_E = (\d+)/) || [])[1]);
  ok(`page script computes with the same SKIN_E as this verifier (${SKIN_E})`, pageSkinE === SKIN_E, `page ${pageSkinE}`);
  const mid2sf = Number(((sMin + sMax) / 2).toPrecision(2));
  ok(`SKIN_E is the midpoint of the sourced span to 2 s.f. (${((sMin + sMax) / 2).toFixed(1)} -> ${mid2sf})`,
     SKIN_E === mid2sf && SKIN_E >= lo50 && SKIN_E <= hi50);
  ok('html says the model value is the middle of the span',
     /computes with <span class="mono">1&thinsp;100<\/span>, the middle of that span/.test(files.html) &&
     /taken as 1100, the middle/.test(files.html));
  // Displayed figures that depend on SKIN_E (dek/body/static readout).
  const oakR = Math.round(contactTemp(SKIN_E, 33, effusivity(MAT.oak), 20));
  const stR = Math.round(contactTemp(SKIN_E, 33, effusivity(MAT.steel), 20));
  ok(`html body says ~${stR} and ~${oakR} °C`, files.html.includes(`meet ~${stR}&nbsp;°C`) && files.html.includes(`meets ~${oakR}&nbsp;°C`));
  const cuTc1 = contactTemp(SKIN_E, 33, effusivity(MAT.copper), 20).toFixed(1);
  ok(`html static contact readout matches copper at SKIN_E (${cuTc1} °C)`,
     files.html.includes(`id="ro-contact" role="status" aria-live="polite">${cuTc1}&nbsp;°C`));

  // Sensitivity: do the page's verdicts hold at both ends of the sourced span?
  const tcAt = (eS, n, T = 20) => contactTemp(eS, 33, effusivity(MAT[n]), T);
  for (const eS of [sMin, sMax]) {
    const tcs = tiles.map((n) => tcAt(eS, n));
    const tag = `skin e=${eS.toFixed(0)}:`;
    ok(`${tag} order copper < steel < glass < oak < foam`, tcs.every((t, i) => i === 0 || t > tcs[i - 1]),
       tcs.map((t) => t.toFixed(2)).join(' / '));
    ok(`${tag} steel meets ~21 (20.8..21.1)`, tcAt(eS, 'steel') >= 20.75 && tcAt(eS, 'steel') <= 21.15, tcAt(eS, 'steel').toFixed(2));
    ok(`${tag} oak meets 28.7..29.5 (~29)`, tcAt(eS, 'oak') >= 28.65 && tcAt(eS, 'oak') <= 29.55, tcAt(eS, 'oak').toFixed(2));
    ok(`${tag} foam stays near 32.6`, Math.abs(tcAt(eS, 'foam') - 32.6) < 0.1, tcAt(eS, 'foam').toFixed(2));
    ok(`${tag} glass reads cold (< 26)`, tcAt(eS, 'glass') < 26, tcAt(eS, 'glass').toFixed(2));
    ok(`${tag} at 50°C copper still meets > oak + 10`, tcAt(eS, 'copper', 50) > tcAt(eS, 'oak', 50) + 10);
  }
  const cross = effusivity(MAT.glass) * (26 - 20) / (33 - 26);
  ok(`glass crosses 26°C at skin e ≈ 1240 (page says "about 1 240")`, Math.abs(cross - 1240) < 5, cross.toFixed(1));
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
