#!/usr/bin/env node
// Verifier for: The Coin That Only Stings (penny-off-a-skyscraper)
// Recomputes EVERY number shown on the page, two independent ways where possible:
//   (1) analytic terminal velocity  v_t = sqrt(2mg / rho*Cd*A)
//       and closed-form quadratic-drag fall  v(h) = v_t*sqrt(1 - exp(-2 g h / v_t^2))
//   (2) numeric RK4 integration of the full ODE  dv/dt = g - (rho*Cd*A/2m) v^2
// The analytic and numeric impact speeds must agree; that is the offline gate.
// Exits 0 iff every check passes.

const RHO = 1.225;          // kg/m^3, ISA sea-level air density (named free choice)
const G   = 9.81;           // m/s^2 (named free choice)
const MPS_TO_MPH = 2.2369362920544;

let pass = 0, fail = 0;
function check(name, cond, got, want) {
  const ok = !!cond;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}` +
    (got !== undefined ? `  got=${got}` + (want !== undefined ? ` want=${want}` : '') : ''));
  ok ? pass++ : fail++;
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ── physics (mirror of the page) ────────────────────────────────────────
const vTerminal = (m, A, cd) => Math.sqrt(2 * m * G / (RHO * cd * A));
const vAnalytic = (vt, h) => vt * Math.sqrt(1 - Math.exp(-2 * G * h / (vt * vt)));
function vNumeric(m, A, cd, h) {          // RK4 in time, march in distance to h
  const k = RHO * cd * A / (2 * m);
  const dt = 0.0005;
  const accel = v => G - k * v * v;
  let v = 0, x = 0;
  while (x < h) {
    const k1 = accel(v), k2 = accel(v + 0.5 * dt * k1),
          k3 = accel(v + 0.5 * dt * k2), k4 = accel(v + dt * k3);
    const vNext = v + (dt / 6) * (k1 + 2 * k2 + 2 * k3 + k4);
    const dx = 0.5 * (v + vNext) * dt;
    if (x + dx >= h) { v = v + ((h - x) / dx) * (vNext - v); x = h; break; }
    v = vNext; x += dx;
  }
  return v;
}
const keOf = (m, v) => 0.5 * m * v * v;
const edOf = (ke, A) => (ke / A) / 1e4;   // J/cm^2

// ── object parameters (must match the page's OBJ array) ─────────────────
const A_disc = d => Math.PI * (d / 2) ** 2;
const OBJ = [
  { id: 'penny', m: 0.0025, A: A_disc(0.01905),               cd: 1.00 },
  { id: 'pen',   m: 0.0060, A: A_disc(0.008),                 cd: 0.80 },
  { id: 'bolt',  m: 0.0300, A: A_disc(0.010),                 cd: 0.90 },
  { id: 'ice',   m: 0.0500, A: Math.PI * (0.0235) ** 2,       cd: 0.47 },
];

console.log('=== penny-off-a-skyscraper :: recompute every displayed number ===\n');

// ── 1. Penny terminal velocity ≈ 25 mph (Bloomfield / Scientific American) ──
const p = OBJ[0];
const vtPenny = vTerminal(p.m, p.A, p.cd);
console.log(`penny A = ${(p.A * 1e4).toFixed(3)} cm^2 (face, d=19.05 mm)`);
check('penny v_t analytic', near(vtPenny, 11.85, 0.15), vtPenny.toFixed(3) + ' m/s');
check('penny v_t in mph ~25 (Bloomfield)', near(vtPenny * MPS_TO_MPH, 26.5, 1.5),
  (vtPenny * MPS_TO_MPH).toFixed(2) + ' mph', '25-27');

// ── 2. Analytic vs numeric impact speed at Empire State roof (two methods) ──
const H_ROOF = 381, H_TIP = 443;
const vaRoof = vAnalytic(vtPenny, H_ROOF);
const vnRoof = vNumeric(p.m, p.A, p.cd, H_ROOF);
check('penny analytic vs numeric impact @381 m agree', near(vaRoof, vnRoof, 0.02),
  `an=${vaRoof.toFixed(4)} num=${vnRoof.toFixed(4)}`);
check('penny impact @381 m is ~terminal (height irrelevant)', near(vnRoof, vtPenny, 0.02),
  vnRoof.toFixed(4) + ' m/s', vtPenny.toFixed(4));

// ── 3. Impact KE ≈ 0.18 J (page states 0.18; "0.15 J" uses ~11 m/s) ────────
const kePenny = keOf(p.m, vnRoof);
check('penny impact KE ≈ 0.18 J', near(kePenny, 0.176, 0.01), kePenny.toFixed(4) + ' J');
check('penny KE far below 1 J', kePenny < 1, kePenny.toFixed(4) + ' J');

// ── 4. Energy density far below perforation threshold (~20 J/cm^2) ─────────
const edPenny = edOf(kePenny, p.A);
check('penny energy density << 20 J/cm^2', edPenny < 0.2, edPenny.toFixed(4) + ' J/cm^2');

// ── 5. Reaches ~terminal within the first ~15 m / 50 ft ────────────────────
const v50ft = vAnalytic(vtPenny, 15.24);      // 50 ft
const pct50 = 100 * v50ft / vtPenny;
check('penny at 50 ft is >90% of terminal', pct50 > 90, pct50.toFixed(1) + '%');
// distance to reach 95% of terminal
const d95 = vtPenny * vtPenny * Math.log(1 / (1 - 0.95 ** 2)) / (2 * G);
check('distance to 95% terminal ~17 m (55 ft)', near(d95, 16.7, 1.0),
  d95.toFixed(1) + ' m (' + (d95 * 3.28084).toFixed(0) + ' ft)');

// ── 6. The 25-vs-65 mph spread is a C_d choice ─────────────────────────────
// solve C_d that makes the penny hit 65 mph (edge-on / MythBusters fired figure)
const v65 = 65 / MPS_TO_MPH;                   // m/s
const cd65 = 2 * p.m * G / (RHO * p.A * v65 * v65);
check('penny C_d≈0.17 reproduces 65 mph (MythBusters)', near(cd65, 0.166, 0.02),
  cd65.toFixed(3));
// even the pessimistic 65 mph penny is under ~1.1 J and did not penetrate a skull
const ke65 = keOf(p.m, v65);
check('65 mph penny KE ~1.1 J (still no penetration in MythBusters)', near(ke65, 1.055, 0.05),
  ke65.toFixed(3) + ' J');

// ── 7. Vacuum contrast: 443 m tip → ~208 mph (Bloomfield's figure) ─────────
const vVac = Math.sqrt(2 * G * H_TIP);
check('vacuum penny from 443 m tip ≈ 208 mph', near(vVac * MPS_TO_MPH, 208, 3),
  (vVac * MPS_TO_MPH).toFixed(1) + ' mph');

// ── 8. Compare the stated model objects; these checks do not predict injury ──
function summarize(o) {
  const vt = vTerminal(o.m, o.A, o.cd);
  const vimp = vNumeric(o.m, o.A, o.cd, H_ROOF);
  const va = vAnalytic(vt, H_ROOF);
  const ke = keOf(o.m, vimp), ed = edOf(ke, o.A);
  return { vt, vimp, va, ke, ed };
}
console.log('\n-- object comparison (impact @ 381 m) --');
for (const o of OBJ) {
  const s = summarize(o);
  console.log(`   ${o.id.padEnd(6)} v_t=${s.vt.toFixed(1)} m/s (${(s.vt * MPS_TO_MPH).toFixed(0)} mph)  ` +
    `KE=${s.ke.toFixed(2)} J  ED=${s.ed.toFixed(2)} J/cm^2  ` +
    `an/num Δ=${Math.abs(s.va - s.vimp).toFixed(4)}`);
  check(`${o.id}: analytic vs numeric agree`, near(s.va, s.vimp, 0.05),
    `Δ=${Math.abs(s.va - s.vimp).toFixed(4)} m/s`);
}
const sPen = summarize(OBJ[1]), sBolt = summarize(OBJ[2]), sIce = summarize(OBJ[3]);
check('pen model v_t ≈ 49 m/s', near(sPen.vt, 48.9, 1.0),
  sPen.vt.toFixed(1) + ' m/s');
check('pen KE far exceeds penny (>6.5 J, ~40x)', sPen.ke > 6.5 && sPen.ke / kePenny > 30,
  sPen.ke.toFixed(2) + ' J (' + (sPen.ke / kePenny).toFixed(0) + 'x penny)');
check('bolt model impact at 381 m ≈ 67.34 m/s, below terminal ≈ 82.45 m/s',
  near(sBolt.vimp, 67.34, 0.05) && near(sBolt.vt, 82.45, 0.05) && sBolt.vimp < sBolt.vt,
  `impact=${sBolt.vimp.toFixed(2)} m/s terminal=${sBolt.vt.toFixed(2)} m/s`);
check('bolt model energy density above 20 J/cm^2', sBolt.ed > 20,
  sBolt.ed.toFixed(1) + ' J/cm^2');
check('ice model impact KE >20 J at 381 m',
  sIce.ke > 20, `KE=${sIce.ke.toFixed(1)} J`);
// Relative speed and energy alone do not establish safety.
check('penny model has lowest terminal speed and impact KE of the four',
  vtPenny < sPen.vt && vtPenny < sBolt.vt && vtPenny < sIce.vt &&
  kePenny < sPen.ke && kePenny < sBolt.ke && kePenny < sIce.ke, 'penny v_t/KE lowest');

// ── 9. Confirm the shipped HTML carries the same object parameters ─────────
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const here = dirname(fileURLToPath(import.meta.url));
const htmlPath = join(here, '..', '..', 'public', 'strata', 'penny-off-a-skyscraper', 'index.html');
let html = '';
try { html = readFileSync(htmlPath, 'utf8'); } catch { /* optional */ }
if (html) {
  check('HTML present & carries penny mass 0.0025', /m:\s*0\.0025/.test(html), 'found');
  check('HTML carries RHO 1.225', /RHO\s*=\s*1\.225/.test(html), 'found');
  check('HTML integrates the drag ODE (RK4 accel term)', /G\s*-\s*k\s*\*\s*vv?\s*\*\s*vv?/.test(html), 'found');
  check('HTML closing tags present (load-bearing)',
    /<\/script>\s*<\/body>\s*<\/html>/.test(html), 'found');
} else {
  console.log('NOTE  shipped HTML not found next to verifier — skipping DOM cross-checks');
}

// ── result ─────────────────────────────────────────────────────────────
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
