#!/usr/bin/env node
// verify-do-lightning-rods-attract-lightning.mjs
//
// Offline gate for /strata/do-lightning-rods-attract-lightning/. It recomputes EVERY
// number the page shows, from nothing but the electrogeometric striking-distance
// relation, the IEC 62305-2 collection-area geometry, the CIGRE first-negative-stroke
// peak-current distribution, and the IEC 62305-3 side-flash formula, and exits 0 only
// if all checks pass. Where possible each fact is verified two independent ways.
//
// The relations (all sourced; see README.md):
//   striking distance / rolling-sphere radius   r = 10 * I^0.65   (r in m, I in kA)  [IEC 62305 EGM basis]
//   inverse                                      I = (r/10)^(1/0.65)
//   ground protection radius of a single rod     rp = sqrt(2*r*h - h^2)  for h < r    [rolling-sphere geometry]
//   IEC 62305-2 equivalent collection area       Ad = L*W + 2*(3H)(L+W) + pi*(3H)^2   [attractive radius 3H]
//   annual interception estimate                 Nd = Ng * Ad * 1e-6   (Ng flashes/km2/yr, Ad in m2)
//   interception efficiency                      P(I > Imin) from the CIGRE first-negative-stroke
//                                                LOW-CURRENT branch log-normal: median 61 kA, beta_ln = 1.33
//   side-flash separation                        s = ki * kc * l / km                 [IEC 62305-3]
//
// Run:  node research/do-lightning-rods-attract-lightning/verify-do-lightning-rods-attract-lightning.mjs

'use strict';

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

// ---- shared physics (identical to the page's inline JS) --------------------------
const EGM_K = 10;     // electrogeometric coefficient (IEC 62305 basis)
const EGM_P = 0.65;   // electrogeometric exponent (IEC 62305 basis)

const rOfI = (I) => EGM_K * Math.pow(I, EGM_P);            // striking distance / sphere radius, m
const IOfr = (r) => Math.pow(r / EGM_K, 1 / EGM_P);        // implied minimum current, kA
const protRadius = (h, r) => Math.sqrt(2 * r * h - h * h); // ground protection radius of one rod, m
const collectionArea = (L, W, H) => L * W + 2 * (3 * H) * (L + W) + Math.PI * (3 * H) * (3 * H);
const strikesPerYear = (Ng, Ad) => Ng * Ad * 1e-6;
const sideFlash = (ki, kc, l, km) => ki * kc * l / km;

// CIGRE / IEEE first-negative-stroke LOW-CURRENT branch (I <= 20 kA): median 61 kA, beta_ln = 1.33.
// Interception efficiency = fraction of downward strokes whose peak current EXCEEDS Imin.
const CIGRE_MEDIAN = 61;   // kA
const CIGRE_BETA   = 1.33; // natural-log standard deviation
// Abramowitz & Stegun 7.1.26 erf (max abs error 1.5e-7)
function erf(x) {
  const s = x < 0 ? -1 : 1; x = Math.abs(x);
  const t = 1 / (1 + 0.3275911 * x);
  const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
  return s * y;
}
const Phi = (z) => 0.5 * (1 + erf(z / Math.SQRT2));
const efficiency = (Imin) => Phi(Math.log(CIGRE_MEDIAN / Imin) / CIGRE_BETA); // P(I > Imin)

// the four standard Lightning Protection Levels (IEC 62305-1)
const LPL = [
  { name: 'I',   r: 20, Imin: 3,  eff: 99 },
  { name: 'II',  r: 30, Imin: 5,  eff: 97 },
  { name: 'III', r: 45, Imin: 10, eff: 91 },
  { name: 'IV',  r: 60, Imin: 16, eff: 84 },
];
const NFPA_R = 46; // m (150 ft) rolling sphere for ordinary structures

// ---- test harness ----------------------------------------------------------------
let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, cond, detail) {
  if (cond) { pass++; console.log(`  PASS  ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? '  ' + detail : ''}`); }
}

console.log('do-lightning-rods-attract-lightning :: offline verifier');
console.log('EGM: r = 10*I^0.65 ; CIGRE low-branch median 61 kA, beta_ln 1.33');
console.log('');

// [1] the four IEC rolling-sphere radii reproduce from their minimum currents (r = 10*I^0.65)
console.log('[1] rolling-sphere radii  r = 10*I^0.65  (kA -> m), rounded to the standard value');
{
  const expect = { 3: 20.42, 5: 28.47, 10: 44.67, 16: 60.63 };
  for (const L of LPL) {
    const r = rOfI(L.Imin);
    check(`10*${L.Imin}^0.65 = ${expect[L.Imin]} -> IEC ${L.r} m`,
      approx(r, expect[L.Imin], 0.02) && approx(Math.round(r / 5) * 5, L.r, 0.01),
      `= ${r.toFixed(2)} m`);
  }
  // independent direction: the tabulated radius back-solves to ~the tabulated minimum current
  for (const L of LPL) {
    const I = IOfr(L.r);
    check(`inverse: I(${L.r} m) rounds to ${L.Imin} kA`, approx(Math.round(I), L.Imin, 0.5),
      `= ${I.toFixed(2)} kA`);
  }
}

// [2] NFPA 780's 46 m sphere back-solves to ~10.5 kA (inverse check)
console.log('\n[2] NFPA 780 fixed 46 m sphere -> striking-distance current');
{
  const I = IOfr(NFPA_R);
  check('I(46 m) = (46/10)^(1/0.65) = 10.46 kA', approx(I, 10.46, 0.02), `= ${I.toFixed(2)} kA`);
  // independent: 10*10.46^0.65 must return 46 m
  check('and 10*10.46^0.65 returns 46 m', approx(rOfI(I), NFPA_R, 1e-6), `= ${rOfI(I).toFixed(2)} m`);
  // NFPA's 46 m sits between IEC LPL II (30) and III (45): stricter than LPL III? no, between III and IV
  check('46 m lies between IEC LPL III (45 m) and LPL IV (60 m)', NFPA_R > 45 && NFPA_R < 60);
}

// [3] interception efficiencies 99/97/91/84 reproduce as P(I > Imin) of the CIGRE low-branch log-normal
console.log('\n[3] interception efficiency = P(I > Imin), CIGRE first-neg-stroke low branch (median 61 kA, beta 1.33)');
{
  const got = {};
  for (const L of LPL) {
    const e = efficiency(L.Imin) * 100;
    got[L.name] = e;
    check(`P(I > ${L.Imin} kA) = ${e.toFixed(2)}% ~ IEC ${L.eff}% (within 1 pp)`,
      approx(e, L.eff, 1.0), `= ${e.toFixed(2)}%`);
  }
  // monotone: stricter class (smaller Imin) => higher efficiency
  check('efficiency decreases as Imin rises (LPL I > II > III > IV)',
    got.I > got.II && got.II > got.III && got.III > got.IV);
  // sanity: the SPEC's originally-proposed median-31.1/sigma_log10-0.265 distribution does NOT reproduce
  // the table (documents why we use the CIGRE low branch). P(I>10) would be ~97%, not 91%.
  const log10 = (x) => Math.log(x) / Math.LN10;
  const wrong = Phi((log10(31.1) - log10(10)) / 0.265) * 100;
  check('control: median-31.1/sigma10-0.265 MISSES 91% at 10 kA (gives ~97%) -> rejected',
    wrong > 95, `= ${wrong.toFixed(1)}%`);
}

// [4] IEC 62305-2 collection area Ad = L*W + 2*(3H)(L+W) + pi*(3H)^2, attractive radius 3H
console.log('\n[4] collection area  Ad = L*W + 2*(3H)(L+W) + pi*(3H)^2  (attractive radius 3H)');
{
  const L = 10, W = 10, H = 10;             // 10 m x 10 m house, 10 m rod
  const Ad = collectionArea(L, W, H);
  // recompute by hand, term by term
  const t1 = L * W, t2 = 2 * (3 * H) * (L + W), t3 = Math.PI * (3 * H) * (3 * H);
  check('attractive radius = 3H = 30 m', approx(3 * H, 30, 1e-9), `= ${3 * H} m`);
  check('Ad(10x10, H=10) = 4127.43 m^2', approx(Ad, 4127.433, 0.01), `= ${Ad.toFixed(3)} m^2`);
  check('term-by-term: 100 + 1200 + 900*pi', approx(t1 + t2 + t3, Ad, 1e-9),
    `${t1} + ${t2} + ${t3.toFixed(2)}`);
  // independent: for a tall isolated rod the pi*(3H)^2 term dominates and grows as H^2
  const Ad2 = collectionArea(10, 10, 20);
  check('doubling rod height ~quadruples the pi*(3H)^2 term', approx(Math.PI * 3600, 4 * Math.PI * 900, 1e-6),
    `pi*(60)^2 = ${(Math.PI * 3600).toFixed(0)} m^2`);
  // annual interception estimate at Ng = 4 flashes/km2/yr
  const Nd = strikesPerYear(4, Ad);
  check('Nd = Ng*Ad*1e-6 at Ng=4 -> ~0.0165 strikes/yr (1 per ~60 yr)', approx(Nd, 0.016510, 1e-4),
    `= ${Nd.toFixed(4)} /yr`);
}

// [5] rolling-sphere protected-zone geometry, and the weak-stroke bypass
console.log('\n[5] single-rod ground protection radius rp = sqrt(2rh - h^2), and the weak-stroke bypass');
{
  const h = 10, r = 20;                     // 10 m rod, LPL I sphere
  const rp = protRadius(h, r);
  check('rp(h=10, r=20) = sqrt(300) = 17.32 m', approx(rp, 17.3205, 1e-3), `= ${rp.toFixed(4)} m`);
  // independent: a sphere centred at (rp, r) is tangent to the rod tip (0,h) and the ground
  const distToTip = Math.hypot(rp - 0, r - h);
  check('sphere centre (rp, r) is exactly r from the rod tip (tangency)', approx(distToTip, r, 1e-6),
    `dist = ${distToTip.toFixed(4)} m = r`);
  // THE BYPASS: a weak 2 kA stroke has striking distance < the LPL I design radius, so it can attach
  // inside the nominally protected zone.
  const rWeak = rOfI(2);
  check('weak 2 kA stroke: striking distance 10*2^0.65 = 15.69 m < 20 m design sphere -> bypass exists',
    rWeak < r, `r_I(2 kA) = ${rWeak.toFixed(2)} m`);
  // and it is exactly the residual: strokes below Imin (3 kA at LPL I) are the ~1% that P(I>Imin) drops
  const residual = (1 - efficiency(3)) * 100;
  check('residual bypass at LPL I ~ 1% (the honest failure fraction)', approx(residual, 1.18, 0.5),
    `= ${residual.toFixed(2)}%`);
  const residualIV = (1 - efficiency(16)) * 100;
  check('residual bypass at LPL IV ~ 16%', approx(residualIV, 15.72, 1.0), `= ${residualIV.toFixed(2)}%`);
}

// [6] side-flash separation s = ki*kc*l/km (IEC 62305-3)
console.log('\n[6] side-flash separation  s = ki*kc*l/km  (IEC 62305-3)');
{
  const ki = 0.08, kc = 0.5, l = 10, km = 1; // LPL I, one of two down-conductors, air, 10 m
  const s = sideFlash(ki, kc, l, km);
  check('LPL I, kc=0.5, air, l=10 m -> s = 0.40 m', approx(s, 0.40, 1e-9), `= ${s.toFixed(2)} m`);
  // material matters: a masonry path (km=0.5) DOUBLES the required air gap
  check('masonry km=0.5 doubles the required separation to 0.80 m',
    approx(sideFlash(ki, kc, l, 0.5), 0.80, 1e-9), `= ${sideFlash(ki, kc, l, 0.5).toFixed(2)} m`);
  // longer run needs more clearance (linear in l)
  check('s is linear in the conductor length l', approx(sideFlash(ki, kc, 20, km), 2 * s, 1e-9));
}

// [7] the counter-intuitive core: SMALLER sphere = STRICTER class
console.log('\n[7] the reversal: a SMALLER sphere is the STRICTER class');
{
  // LPL I uses the smallest sphere (20 m) yet is the most stringent: it dips into gaps a big sphere floats over
  check('LPL I sphere (20 m) is the SMALLEST of the four', LPL[0].r === Math.min(...LPL.map(l => l.r)));
  check('LPL I is the STRICTEST (highest efficiency, lowest Imin caught)',
    LPL[0].eff === Math.max(...LPL.map(l => l.eff)) && LPL[0].Imin === Math.min(...LPL.map(l => l.Imin)));
  // demonstrate the sag: two 10 m rods 10 m apart. The 20 m sphere dips LESS between them than a 60 m sphere?
  // No: the SMALLER sphere sags MORE (touches lower), so it is the one that reaches the ridge between rods.
  const a = 5; // half-separation, m
  const sag = (r) => r - Math.sqrt(r * r - a * a); // how far the sphere underside dips below the two tips
  check('between two rods 10 m apart, the 20 m sphere dips deeper than the 60 m sphere',
    sag(20) > sag(60), `sag20 = ${sag(20).toFixed(3)} m > sag60 = ${sag(60).toFixed(3)} m`);
}

// [8] the shipped page displays exactly these numbers (read the HTML, assert presence)
console.log('\n[8] the shipped page shows the same figures');
{
  const here = dirname(fileURLToPath(import.meta.url));
  const htmlPath = join(here, '..', '..', 'public', 'strata', 'do-lightning-rods-attract-lightning', 'index.html');
  let html = '';
  try { html = readFileSync(htmlPath, 'utf8'); } catch (e) { html = ''; }
  const must = ['20', '30', '45', '60', '46', '10.5', '3 kA', '5 kA', '10 kA', '16 kA',
    '99', '97', '91', '84', '10*I^0.65', '4127', '17.3', '15.7', '0.40', '61', '1.33'];
  for (const m of must) {
    check(`page contains "${m}"`, html.indexOf(m) !== -1);
  }
}

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