// verify.mjs — the aerodynamics behind the stratum
// "The Air That Got There First" (/strata/the-air-that-got-there-first/).
//
// The claim the page corrects — the single most repeated wrong explanation of
// flight on the internet, in museums, and in more than a few textbooks:
//
//   "The air going over the curved top of a wing has farther to travel, so it
//    must go faster to meet the air underneath at the trailing edge at the same
//    time; faster air has lower pressure (Bernoulli); the pressure difference
//    lifts the wing."
//
// The fatal premise is the part nobody states out loud: that the two parcels of
// air which split at the leading edge must REUNITE at the trailing edge — the
// "equal transit time" assumption. They do not. The air over the top arrives at
// the trailing edge FIRST, and by a wide margin. It never waits for the bottom.
//
// This script settles it from scratch, with no libraries, using the exact
// closed-form potential flow around a Joukowski airfoil (a circle conformally
// mapped to a wing). What it proves:
//
//   1. KUTTA CONDITION — the circulation Gamma that makes the rear stagnation
//      point sit exactly on the sharp trailing edge is Gamma = 4*pi*a*U*sin(a-b).
//      We verify the closed form by checking that the complex velocity in the
//      circle plane vanishes at the trailing-edge pre-image (dw/dzeta = 0 there).
//
//   2. EQUAL-TRANSIT-TIME IS FALSE — release two marker parcels side by side in
//      the oncoming stream, one that goes over the top and one under. Advect both
//      through the EXACT velocity field for the same physical time. The top
//      parcel reaches the trailing-edge plane many lengths ahead of the bottom
//      one. We report the ratio of transit times: it is nowhere near 1.
//
//   3. BERNOULLI AND NEWTON ARE THE SAME LIFT, NOT RIVAL ONES — compute the lift
//      two independent ways: (a) Kutta-Joukowski, L' = rho*U*Gamma (the
//      circulation bookkeeping), and (b) the integral of pressure over the wing
//      surface with p from Bernoulli, q from the exact field. They agree to
//      better than 1%. The popular framing pits "Bernoulli vs Newton"; the model
//      shows they are one flow described two ways.
//
//   4. THE TOP REALLY IS FASTER (just not for the stated reason) — the maximum
//      speed over the upper surface exceeds the freestream, the lower surface is
//      slower, and the suction (low pressure) is concentrated near the leading
//      edge on top — not a gentle even push from a longer path.
//
//   run:  node research/the-air-that-got-there-first/verify.mjs
//
// No dependencies. Every headline number the page shows is recomputed here.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};

// ---- minimal complex arithmetic -------------------------------------------
const C  = (re, im = 0) => ({ re, im });
const add = (a, b) => C(a.re + b.re, a.im + b.im);
const sub = (a, b) => C(a.re - b.re, a.im - b.im);
const mul = (a, b) => C(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
const sca = (a, s) => C(a.re * s, a.im * s);
const conj = (a) => C(a.re, -a.im);
const abs2 = (a) => a.re * a.re + a.im * a.im;
const cabs = (a) => Math.hypot(a.re, a.im);
const div = (a, b) => { const d = abs2(b); return C((a.re * b.re + a.im * b.im) / d, (a.im * b.re - a.re * b.im) / d); };
const inv = (a) => { const d = abs2(a); return C(a.re / d, -a.im / d); };
const csqrt = (a) => {                       // principal square root
  const r = cabs(a), re = Math.sqrt((r + a.re) / 2);
  let im = Math.sqrt((r - a.re) / 2);
  if (a.im < 0) im = -im;
  return C(re, im);
};

// ---- airfoil geometry & flow parameters -----------------------------------
// Joukowski map  z = zeta + c^2/zeta.  A circle in the zeta-plane of radius a,
// centred at mu, that PASSES THROUGH zeta = +c maps to an airfoil with a sharp
// (cusped) trailing edge at z = 2c. Real(mu) < 0 sets thickness; Imag(mu) > 0
// sets camber (curve-up).
const c   = 1;               // map scale  -> trailing edge at z = 2c = 2
const U   = 1;               // freestream speed
const rho = 1;               // density (units arbitrary; lift compared internally)
const mu  = C(-0.10, 0.10);  // circle centre -> ~moderate thickness + camber

const a    = cabs(sub(C(c, 0), mu));          // radius: circle passes through z=c
const cMm  = sub(C(c, 0), mu);                 // (c - mu)
const beta = Math.atan2(cMm.im, cMm.re);       // angle of trailing-edge pre-image
// forward declaration: chord length (LE-to-TE), filled after the maps below.
let chordLen = 0;

// Circulation from the Kutta condition (closed form), as a function of AoA.
const Gamma = (alpha) => 4 * Math.PI * a * U * Math.sin(alpha - beta);

// Complex potential itself in the circle (zeta) plane (for the streamfunction):
//   w = U( xi e^{-i a} + a^2 e^{i a}/xi ) + (i Gamma / 2 pi) ln(xi),  xi = zeta - mu
const clog = (z) => C(Math.log(cabs(z)), Math.atan2(z.im, z.re));
const wFull = (zeta, alpha) => {
  const xi   = sub(zeta, mu);
  const eMia = C(Math.cos(alpha), -Math.sin(alpha));
  const ePia = C(Math.cos(alpha),  Math.sin(alpha));
  const t1   = sca(add(mul(xi, eMia), sca(mul(ePia, inv(xi)), a * a)), U);
  const t2   = mul(C(0, Gamma(alpha) / (2 * Math.PI)), clog(xi));
  return add(t1, t2);
};
// Streamfunction at a PHYSICAL point z (constant along streamlines).
const psiAt = (z, alpha) => wFull(zetaOf(z), alpha).im;

// Complex potential derivative in the circle (zeta) plane:
//   dw/dzeta = U( e^{-i a} - a^2 e^{i a}/(zeta-mu)^2 ) + i Gamma / (2 pi (zeta-mu))
const dwdzeta = (zeta, alpha) => {
  const xi   = sub(zeta, mu);                  // zeta - mu
  const eMia = C(Math.cos(alpha), -Math.sin(alpha));
  const ePia = C(Math.cos(alpha),  Math.sin(alpha));
  const t1   = mul(eMia, C(1, 0));
  const t2   = sca(mul(ePia, inv(mul(xi, xi))), a * a);
  const free = sca(sub(t1, t2), U);
  const circ = mul(C(0, Gamma(alpha) / (2 * Math.PI)), inv(xi)); // i*Gamma/(2pi) / xi
  return add(free, circ);
};

// Map derivative dz/dzeta = 1 - c^2/zeta^2  (zero at zeta = +/- c).
const dzdzeta = (zeta) => sub(C(1, 0), sca(inv(mul(zeta, zeta)), c * c));

// Forward map z = zeta + c^2/zeta.
const zOf = (zeta) => add(zeta, sca(inv(zeta), c * c));

// Inverse map: zeta = ( z +/- sqrt(z^2 - 4c^2) ) / 2, pick the EXTERIOR root
// (the one outside the circle, |zeta - mu| >= a).
const zetaOf = (z) => {
  const root = csqrt(sub(mul(z, z), C(4 * c * c, 0)));
  const p = sca(add(z, root), 0.5);
  const m = sca(sub(z, root), 0.5);
  return cabs(sub(p, mu)) >= cabs(sub(m, mu)) ? p : m;
};

// PHYSICAL velocity as a vector (complex u+iv) at a physical point z.
// complex velocity is dw/dz = (dw/dzeta)/(dz/dzeta); the actual velocity vector
// is its conjugate.
const velAt = (z, alpha) => {
  const zeta = zetaOf(z);
  const w = div(dwdzeta(zeta, alpha), dzdzeta(zeta));
  return conj(w);                              // u + i v
};

// Flow speed on the airfoil SURFACE at circle angle theta (skips theta where
// dz/dzeta = 0, i.e. the trailing edge).
const surfaceSpeed = (theta, alpha) => {
  const zeta = add(mu, C(a * Math.cos(theta), a * Math.sin(theta)));
  const num = cabs(dwdzeta(zeta, alpha));
  const den = cabs(dzdzeta(zeta));
  return num / den;
};

// chord = distance from the leading-edge point to the trailing edge (z = 2c).
{
  const zTE = zOf(C(c, 0));
  const zLE = zOf(add(mu, C(a * Math.cos(beta + Math.PI), a * Math.sin(beta + Math.PI))));
  chordLen = cabs(sub(zTE, zLE));
}

// ===========================================================================
console.log('\nThe Air That Got There First — aerodynamics verifier\n');
console.log(`airfoil:  c=${c}  mu=(${mu.re},${mu.im})  a=${a.toFixed(5)}  beta=${(beta*180/Math.PI).toFixed(3)} deg`);
console.log(`trailing edge maps to z = ${zOf(C(c,0)).re.toFixed(4)} (expected 2c=${2*c})\n`);

// ---- 1. Kutta condition: dw/dzeta = 0 at the trailing-edge pre-image -------
const deg = (d) => d * Math.PI / 180;
for (const adeg of [0, 4, 8]) {
  const v = dwdzeta(C(c, 0), deg(adeg));
  ok(`Kutta: |dw/dzeta| = 0 at trailing edge (AoA ${adeg} deg)`,
     cabs(v) < 1e-9, `|dw/dzeta|=${cabs(v).toExponential(2)}  Gamma=${Gamma(deg(adeg)).toFixed(4)}`);
}

// ---- 2. EQUAL TRANSIT TIME IS FALSE ----------------------------------------
// This mirrors the real smoke-tunnel experiment (Babinsky, Cambridge): release a
// thin filament of dye straddling the dividing streamline that hits the nose; one
// half goes over the top, one half under. Advect through the EXACT velocity field
// and watch when each reaches the trailing-edge plane x = 2c. The over-the-top
// half arrives FIRST; by the time the under half gets there, the top half is far
// downstream. They never reunite.
const alpha = deg(6);                          // 6 deg angle of attack

// RK4 advection of one parcel until it crosses x = xTarget; returns crossing time.
function transit(z0, alpha, xTarget = 2 * c, dt = 1e-4, maxSteps = 8_000_000) {
  let z = z0, t = 0;
  for (let n = 0; n < maxSteps; n++) {
    const k1 = velAt(z, alpha);
    const k2 = velAt(add(z, sca(k1, dt / 2)), alpha);
    const k3 = velAt(add(z, sca(k2, dt / 2)), alpha);
    const k4 = velAt(add(z, sca(k3, dt)), alpha);
    const zNext = add(z, sca(add(add(k1, sca(k2, 2)), add(sca(k3, 2), k4)), dt / 6));
    t += dt;
    if (zNext.re >= xTarget && z.re < xTarget) {
      const frac = (xTarget - z.re) / (zNext.re - z.re);
      return { t: t - dt + dt * frac, z: zNext, ok: true };
    }
    z = zNext;
    if (cabs(z) > 60) break;
  }
  return { t, z, ok: false };
}
// RK4 for a fixed elapsed time; returns final position (to read off the "lead").
function advanceFor(z0, alpha, T, dt = 1e-4) {
  let z = z0;
  const N = Math.round(T / dt);
  for (let n = 0; n < N; n++) {
    const k1 = velAt(z, alpha);
    const k2 = velAt(add(z, sca(k1, dt / 2)), alpha);
    const k3 = velAt(add(z, sca(k2, dt / 2)), alpha);
    const k4 = velAt(add(z, sca(k3, dt)), alpha);
    z = add(z, sca(add(add(k1, sca(k2, 2)), add(sca(k3, 2), k4)), dt / 6));
  }
  return z;
}

// Locate the dividing streamline's release height at xRel by matching the
// streamfunction to its value at the forward stagnation point (exact).
const xRel    = -2.5;
const thetaS  = Math.PI + 2 * alpha - beta;                 // front stagnation angle (exact)
const zetaS   = add(mu, C(a * Math.cos(thetaS), a * Math.sin(thetaS)));
const psiDiv  = wFull(zetaS, alpha).im;
// bisection on release height y for psiAt(xRel,y) = psiDiv
let yLo = -1.0, yHi = 1.0;
const fpsi = (y) => psiAt(C(xRel, y), alpha) - psiDiv;
// ensure a sign change brackets the root
let sLo = Math.sign(fpsi(yLo)), sHi = Math.sign(fpsi(yHi));
for (let i = 0; i < 80 && sLo === sHi; i++) { yLo -= 0.5; sLo = Math.sign(fpsi(yLo)); }
let yDiv = 0;
for (let i = 0; i < 100; i++) {
  const ym = (yLo + yHi) / 2, sm = Math.sign(fpsi(ym));
  if (sm === sLo) yLo = ym; else yHi = ym;
  yDiv = ym;
}

console.log(`\ndividing streamline released at (x=${xRel}, y=${yDiv.toFixed(4)});  filament half-width eps:`);
let leadResult = null;
for (const eps of [0.02, 0.005]) {            // two filament thicknesses
  const top = transit(C(xRel, yDiv + eps), alpha);
  const bot = transit(C(xRel, yDiv - eps), alpha);
  if (!(top.ok && bot.ok)) { console.log(`  eps=${eps}: a parcel stalled (near a stagnation point)`); continue; }
  // where is the top half when the bottom half reaches the trailing edge?
  const zTopAtTb = advanceFor(C(xRel, yDiv + eps), alpha, bot.t);
  const leadChords = (zTopAtTb.re - 2 * c) / chordLen;
  const pct = (bot.t - top.t) / bot.t * 100;
  console.log(`  eps=${eps.toFixed(3)}:  t_top=${top.t.toFixed(4)}  t_bot=${bot.t.toFixed(4)}` +
              `  -> top arrives ${pct.toFixed(1)}% sooner; when bottom reaches the TE, top is ${leadChords.toFixed(2)} chords past it`);
  if (eps === 0.02) leadResult = { top, bot, pct, leadChords };
}
console.log('');
ok('the OVER-THE-TOP parcel reaches the trailing edge FIRST',
   leadResult && leadResult.top.t < leadResult.bot.t,
   leadResult ? `t_top=${leadResult.top.t.toFixed(4)} < t_bot=${leadResult.bot.t.toFixed(4)}` : '');
ok('the lead is LARGE — not the ~0% the equal-transit myth predicts',
   leadResult && leadResult.pct > 10,
   leadResult ? `top arrives ${leadResult.pct.toFixed(1)}% sooner; ${leadResult.leadChords.toFixed(2)} chords ahead at the TE` : '');

// ---- 3. LIFT TWO WAYS: Kutta-Joukowski vs surface-pressure integral --------
// (a) Kutta-Joukowski
const L_KJ = rho * U * Gamma(alpha);
// (b) integral of pressure over the surface. p = p_inf + 0.5*rho*(U^2 - q^2)
// (Bernoulli). Force = -closed integral of p * n ds, n outward normal in z-plane.
// Parametrise the circle by theta; map to z; use the physical surface element
// and normal derived from dz = (dz/dzeta) dzeta.
function liftFromPressure(alpha, N = 200000) {
  let Fx = 0, Fy = 0;
  for (let i = 0; i < N; i++) {
    const th = (i + 0.5) / N * 2 * Math.PI;       // midpoint, avoids theta=0 (TE)
    const zeta = add(mu, C(a * Math.cos(th), a * Math.sin(th)));
    const dz = mul(dzdzeta(zeta), C(-a * Math.sin(th), a * Math.cos(th))); // dz/dtheta
    const ds = cabs(dz) * (2 * Math.PI / N);
    // outward normal in z-plane: rotate the (outward) tangent. The circle's
    // outward normal in zeta is (cos th, sin th); map direction via dz/dzeta and
    // renormalise, then it is the surface tangent's perpendicular. Simpler: the
    // unit outward normal n = -i * (dz/dtheta)/|dz/dtheta| for a CCW contour
    // gives the OUTWARD normal of the enclosed region.
    const tHat = sca(dz, 1 / cabs(dz));            // unit tangent (CCW)
    const nHat = C(tHat.im, -tHat.re);             // rotate -90 deg -> outward normal
    const q = cabs(dwdzeta(zeta)) / cabs(dzdzeta(zeta) === 0 ? C(1e-12,0) : dzdzeta(zeta));
    const qspeed = cabs(div(dwdzeta(zeta, alpha), dzdzeta(zeta)));
    const p = 0.5 * rho * (U * U - qspeed * qspeed); // gauge p_inf = 0
    Fx += -p * nHat.re * ds;
    Fy += -p * nHat.im * ds;
  }
  // lift is the component perpendicular to the freestream (which points at angle alpha)
  const L = -Fx * Math.sin(alpha) + Fy * Math.cos(alpha);
  const D = Fx * Math.cos(alpha) + Fy * Math.sin(alpha);
  return { L, D };
}
const press = liftFromPressure(alpha);
console.log('');
ok('Kutta-Joukowski lift L = rho*U*Gamma is positive (upward) at +AoA',
   L_KJ > 0, `L_KJ=${L_KJ.toFixed(4)}`);
const relErr = Math.abs(press.L - L_KJ) / Math.abs(L_KJ) * 100;
ok('pressure-integral lift (Bernoulli) matches Kutta-Joukowski to < 1%',
   relErr < 1, `L_pressure=${press.L.toFixed(4)}  L_KJ=${L_KJ.toFixed(4)}  diff=${relErr.toFixed(3)}%`);
ok('drag is ~0 (d Alembert paradox: inviscid model has no drag)',
   Math.abs(press.D) < 1e-2 * Math.abs(L_KJ), `D=${press.D.toExponential(2)}`);

// ---- 4. Top surface faster; suction near the leading edge ------------------
let qTopMax = 0, qBotMax = 0;
for (let i = 1; i < 2000; i++) {
  const th = i / 2000 * 2 * Math.PI;
  const s = surfaceSpeed(th, alpha);
  // upper surface ~ theta in (0, pi) maps near the top; use z.im sign to classify
  const zeta = add(mu, C(a * Math.cos(th), a * Math.sin(th)));
  const z = zOf(zeta);
  if (z.im > 0) qTopMax = Math.max(qTopMax, s);
  else qBotMax = Math.max(qBotMax, s);
}
console.log('');
ok('peak speed over the TOP exceeds the freestream U', qTopMax > U,
   `q_top_max=${qTopMax.toFixed(3)} U  (vs U=${U})`);
ok('top surface peak speed exceeds bottom surface peak speed', qTopMax > qBotMax,
   `q_top_max=${qTopMax.toFixed(3)}  q_bot_max=${qBotMax.toFixed(3)}`);

// ---- lift slope sanity: ~2*pi per radian (thin-airfoil theory) -------------
// Cl = L / (0.5 rho U^2 chord).
const ch = chordLen;
const Cl = (al) => (rho * U * Gamma(al)) / (0.5 * rho * U * U * ch);
const slope = (Cl(deg(5)) - Cl(deg(3))) / (deg(5) - deg(3)); // dCl/dalpha
ok('lift-curve slope dCl/dAoA is within ~15% of 2*pi (thin-airfoil theory)',
   Math.abs(slope - 2 * Math.PI) / (2 * Math.PI) < 0.15,
   `dCl/dAoA=${slope.toFixed(3)} /rad  (2*pi=${(2*Math.PI).toFixed(3)});  chord=${ch.toFixed(4)}`);

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