// verify-can-a-magnet-erase-your-phone-or-ssd.mjs — the physics behind the stratum
// "The Field That Can't Reach the Data" (/strata/can-a-magnet-erase-your-phone-or-ssd/).
//
// This script checks the cylinder arithmetic and nominal coercivity comparisons.
// It does not prove actual erasure, absence of domain motion, or real-device field bounds:
//
//   1. A magnet is not a point. Modelled as a uniformly-magnetised cylinder
//      (remanence Br, radius R, length L), the EXACT on-axis field is
//         B(z) = (Br/2) * [ (L+z)/sqrt(R^2+(L+z)^2)  -  z/sqrt(R^2+z^2) ]
//      with z the distance from the pole face. At z=0 this equals the surface
//      field B_surface = (Br/2)*L/sqrt(R^2+L^2) — the NEAR-FIELD CLAMP that a raw
//      1/z^3 dipole would violate (it diverges as z->0). Far away it decays as
//      1/z^3 (the dipole limit). We verify both ends two independent ways.
//
//   2. Coercivity read into a B-field: 1 Oe = 1 gauss = 0.1 mT (the vacuum
//      correspondence). Garner says, "One+ gauss effectively eliminates one oersted."
//      The nominal coercivity comparisons are
//      LoCo magstripe 300 Oe -> 30 mT, HiCo 2750 Oe -> 275 mT, HDD 5000 Oe -> 500 mT.
//
//   3. The surface fields the page prints for each magnet fall out of (Br,R,L)
//      and land in the sourced ranges (fridge ~5 mT within 1-10; neodymium 0.3-1.4 T).
//
//   4. The calculator compares model fields with the selected nominal coercivities:
//      neodymium at contact is AT RISK for LoCo but BELOW the HDD value;
//      the fridge model is BELOW all selected magnetic-media values; MagSafe is
//      AT RISK for LoCo but BELOW HiCo. Flash is IMMUNE to magnetic degaussing.
//      These labels do not assert a threshold for the first domain motion or a complete wipe.
//
//   run:  node research/can-a-magnet-erase-your-phone-or-ssd/verify-can-a-magnet-erase-your-phone-or-ssd.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;

// ── magnets: uniformly-magnetised cylinder, Br in T, R & L in mm ─────────────
const MAGS = {
  fridge:  { name: 'Fridge magnet',    Br: 0.38, R: 12, L: 0.3  },
  magsafe: { name: 'MagSafe / phone',  Br: 1.30, R: 5,  L: 0.35 },
  neo:     { name: 'Neodymium button', Br: 1.30, R: 10, L: 10   },
  speaker: { name: 'Speaker magnet',   Br: 0.40, R: 25, L: 8    },
};

// EXACT on-axis field of a uniformly-magnetised cylinder; z in mm, returns Tesla.
const fieldT = (m, z) => {
  const a = (m.L + z) / Math.sqrt(m.R * m.R + (m.L + z) * (m.L + z));
  const b = z / Math.sqrt(m.R * m.R + z * z);
  return (m.Br / 2) * (a - b);
};
const surfaceMT = (m) => fieldT(m, 0) * 1000;
const fieldMT = (m, zmm) => fieldT(m, zmm) * 1000;

// ── media: coercivity (Oe) -> nominal coercivity comparison (mT) via 1 Oe = 0.1 mT ─────────
const OE_TO_MT = 0.1;
const MEDIA = {
  flash: { name: 'Phone / SSD', immune: true,  oe: null },
  hdd:   { name: 'Hard drive',  immune: false, oe: 5000 },
  loco:  { name: 'Hotel key / transit (LoCo)', immune: false, oe: 300 },
  hico:  { name: 'Bank card (HiCo)', immune: false, oe: 2750 },
};
const thresholdMT = (x) => x.immune ? null : x.oe * OE_TO_MT;

// ── 1. Oe -> mT conversion is the vacuum identity (independent check) ────────
// 1 Oe of H corresponds, in vacuum, to B = mu0 * H with H = 1000/(4*pi) A/m.
// mu0 = 4*pi*1e-7 T*m/A  =>  B = 4*pi*1e-7 * 1000/(4*pi) = 1e-4 T = 0.1 mT. QED.
console.log('\n— 1 Oe = 1 gauss = 0.1 mT (vacuum identity) —');
{
  const mu0 = 4 * Math.PI * 1e-7;
  const H_oneOe = 1000 / (4 * Math.PI); // A/m equivalent of 1 oersted
  const B_mT = mu0 * H_oneOe * 1000;    // -> mT
  ok('1 Oe -> 0.1 mT from mu0*H', approx(B_mT, 0.1, 1e-9), `= ${B_mT.toFixed(4)} mT`);
  ok('5000 Oe HDD -> 500 mT', approx(5000 * OE_TO_MT, 500, 1e-9));
  ok('300 Oe LoCo -> 30 mT',  approx(300 * OE_TO_MT, 30, 1e-9));
  ok('2750 Oe HiCo -> 275 mT', approx(2750 * OE_TO_MT, 275, 1e-9));
}

// ── 2. Surface fields fall out of (Br,R,L) and hit sourced ranges ───────────
console.log('\n— surface field B_surface = (Br/2)*L/sqrt(R^2+L^2) —');
{
  // independent recompute of the surface formula (not via fieldT)
  for (const [id, m] of Object.entries(MAGS)) {
    const direct = (m.Br / 2) * (m.L / Math.sqrt(m.R * m.R + m.L * m.L)) * 1000; // mT
    const viaField = surfaceMT(m);
    ok(`${m.name.padEnd(16)} B_surf ${direct.toFixed(1)} mT  (two ways agree)`,
       approx(direct, viaField, 1e-9), `Δ=${Math.abs(direct - viaField).toExponential(1)}`);
  }
  // pinned values the page prints (chip subtitles + table)
  ok('fridge  B_surf ~ 4.7 mT (within sourced 1-10 mT)', approx(surfaceMT(MAGS.fridge), 4.75, 0.15) &&
     surfaceMT(MAGS.fridge) >= 1 && surfaceMT(MAGS.fridge) <= 10, `${surfaceMT(MAGS.fridge).toFixed(2)}`);
  ok('magsafe B_surf ~ 45 mT',  approx(surfaceMT(MAGS.magsafe), 45.4, 0.6), `${surfaceMT(MAGS.magsafe).toFixed(1)}`);
  ok('neo     B_surf ~ 460 mT (within sourced 0.3-1.4 T)', approx(surfaceMT(MAGS.neo), 459.6, 1.0) &&
     surfaceMT(MAGS.neo) >= 300 && surfaceMT(MAGS.neo) <= 1400, `${surfaceMT(MAGS.neo).toFixed(1)}`);
  ok('speaker cylinder B_surf ~ 61 mT (illustrative geometry)', approx(surfaceMT(MAGS.speaker), 61.0, 0.6),
     `${surfaceMT(MAGS.speaker).toFixed(1)}`);
}

// ── 3. Near-field clamp + far-field 1/z^3 (the hazard the model must honour) ─
console.log('\n— near-field clamp at z=0, far-field 1/z^3 slope —');
{
  const m = MAGS.neo;
  // (a) clamp: B(0) is finite and equals B_surface (a raw dipole B ~ 1/z^3 would diverge)
  ok('B(0) finite = B_surface (no 1/z^3 blow-up)', Number.isFinite(fieldMT(m, 0)) &&
     approx(fieldMT(m, 0), surfaceMT(m), 1e-9), `B(0)=${fieldMT(m, 0).toFixed(1)} mT`);
  // (b) monotone decreasing away from the face
  let mono = true, prev = fieldMT(m, 0);
  for (let z = 1; z <= 200; z++) { const b = fieldMT(m, z); if (b > prev + 1e-9) mono = false; prev = b; }
  ok('field strictly decreases with distance', mono);
  // (c) far field: log-log slope of B vs z tends to -3 (dipole) as z >> R,L.
  //     Measured far out (1-2 m) where the cylinder is fully in its asymptotic regime.
  const z1 = 1000, z2 = 2000;
  const slope = (Math.log(fieldT(m, z2)) - Math.log(fieldT(m, z1))) / (Math.log(z2) - Math.log(z1));
  ok('far-field slope -> -3 (dipole 1/z^3)', approx(slope, -3, 0.05), `slope=${slope.toFixed(3)}`);
  // (d) independent far-field cross-check: point-dipole moment m_dip = Br*V/mu0,
  //     B_axial ~ mu0*m_dip/(2*pi*r^3) with r measured from the magnet CENTRE.
  const mu0 = 4 * Math.PI * 1e-7;
  const R = m.R / 1000, L = m.L / 1000;               // -> metres
  const V = Math.PI * R * R * L;                      // volume
  const mdip = (m.Br / mu0) * V;                       // magnetic moment (A*m^2)
  const rCentre = (100 + m.L / 2) / 1000;             // centre-distance for z=100mm face-distance
  const Bdip = mu0 * mdip / (2 * Math.PI * rCentre ** 3) * 1000; // mT
  const Bcyl = fieldMT(m, 100);
  ok('cylinder field ~ point-dipole at 10 cm (independent)', approx(Bdip, Bcyl, 0.5 * Bcyl) &&
     Math.abs(Bdip - Bcyl) / Bcyl < 0.15, `cyl=${Bcyl.toFixed(3)} dipole=${Bdip.toFixed(3)} mT`);
}

// ── 4. Verdict logic at the pinned example points ───────────────────────────
console.log('\nModel comparisons: field at distance vs nominal coercivity');
const verdict = (magId, mediaId, cm) => {
  const med = MEDIA[mediaId];
  if (med.immune) return 'IMMUNE';
  const B = fieldMT(MAGS[magId], cm * 10);
  return B >= thresholdMT(med) ? 'AT RISK' : 'BELOW';
};
const check = (magId, mediaId, cm, want) => {
  const got = verdict(magId, mediaId, cm);
  const B = MEDIA[mediaId].immune ? null : fieldMT(MAGS[magId], cm * 10);
  ok(`${MAGS[magId].name} @ ${cm}cm vs ${MEDIA[mediaId].name} -> ${got}`, got === want,
     B === null ? '(charge storage)' : `B=${B.toFixed(1)} mT / thr=${thresholdMT(MEDIA[mediaId])} mT`);
};

// Flash charge storage is immune to magnetic degaussing; this is not an electronics test.
check('neo', 'flash', 0, 'IMMUNE');
check('speaker', 'flash', 0, 'IMMUNE');

// These four model fields are below the selected nominal HDD coercivity.
check('fridge', 'hdd', 0, 'BELOW');
check('magsafe', 'hdd', 0, 'BELOW');
check('speaker', 'hdd', 0, 'BELOW');
check('neo', 'hdd', 0, 'BELOW');       // even a strong neo at the bare platter: 460 < 500 mT

// The model fields for neo and MagSafe exceed the selected nominal LoCo coercivity.
check('neo', 'loco', 0, 'AT RISK');   // 460 mT >> 30 mT
check('magsafe', 'loco', 0, 'AT RISK'); // 45 mT > 30 mT in this cylinder model
check('fridge', 'loco', 0, 'BELOW');   // 4.7 mT < 30 mT in this cylinder model

// Compare model fields with the selected nominal HiCo coercivity.
check('magsafe', 'hico', 0, 'BELOW');  // 45 mT < 275 mT
check('neo', 'hico', 0, 'AT RISK');   // 460 mT > 275 mT at contact

// The neo model field crosses below the selected LoCo comparison before 3 cm.
check('neo', 'loco', 3, 'BELOW');      // ~13.9 mT at 3 cm < 30 mT
ok('neo field crosses the LoCo comparison between contact and 3 cm',
   verdict('neo', 'loco', 0) === 'AT RISK' && verdict('neo', 'loco', 3) === 'BELOW');

// ── 5. Pinned numeric field values the page's check-line prints ─────────────
console.log('\n— pinned field values (mT) —');
ok('neo @ 0 cm  = 459.6 mT', approx(fieldMT(MAGS.neo, 0), 459.6, 0.5), `${fieldMT(MAGS.neo, 0).toFixed(1)}`);
ok('neo @ 2 cm  = 35.3 mT',  approx(fieldMT(MAGS.neo, 20), 35.27, 0.2), `${fieldMT(MAGS.neo, 20).toFixed(2)}`);
ok('neo @ 3 cm  = 13.9 mT',  approx(fieldMT(MAGS.neo, 30), 13.95, 0.2), `${fieldMT(MAGS.neo, 30).toFixed(2)}`);
ok('magsafe @ 0 cm = 45.4 mT', approx(fieldMT(MAGS.magsafe, 0), 45.39, 0.2), `${fieldMT(MAGS.magsafe, 0).toFixed(2)}`);

// 6. Sourced counterexample to a uniform MagSafe upper bound.
// Sensors 23 (2023), 1209, sections 3.1 and 3.2, iPhone 13 Pro annular array:
// https://mdpi-res.com/d_attachment/sensors/sensors-23-01209/article_deploy/sensors-23-01209.pdf
console.log('\nMagSafe model compared with measured annular-array maxima');
{
  const near = fieldMT(MAGS.magsafe, 0.1);
  const farther = fieldMT(MAGS.magsafe, 4.4);
  ok('model is below measured 68.8 mT at 0.1 mm: not an upper bound',
     near < 68.8, `model=${near.toFixed(6)} mT`);
  ok('model is above measured 8.9 mT at 4.4 mm: discrepancy changes sign',
     farther > 8.9, `model=${farther.toFixed(6)} mT`);
  const measuredFall = 1 - 8.9 / 68.8;
  const modelFall = 1 - farther / near;
  ok('measured initial fractional fall is faster than the model (X6)',
     measuredFall > modelFall, `measured=${(100 * measuredFall).toFixed(1)}%, model=${(100 * modelFall).toFixed(1)}%`);
}

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