#!/usr/bin/env node
// Verifier for the stratum "Faster Than the Wind That Pushes It"
// (public/strata/faster-than-the-wind/).
//
// Every number the page asserts as *derived* is recomputed here from first
// principles. What the page does NOT derive — the world records, the bet, the
// aerodynamic drag ceilings — is sourced in the page's own apparatus, not here.
//
// Run: node research/faster-than-the-wind/verify.mjs
// Exit 0 and print "N/N checks passed" on success.
//
// Conventions (all velocities are vectors over the GROUND, in the same units):
//   Vtw  = velocity of the air relative to the ground  = the "true wind"
//   Vb   = velocity of the craft relative to the ground
//   Vaw  = apparent wind = velocity of the air relative to the craft = Vtw - Vb
// The sailor feels Vaw; a sail generates drive from it. Nothing here depends on
// the choice of units, so numbers are dimensionless multiples of wind speed
// except where a real record is quoted.

let passed = 0, failed = 0;
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
function check(name, cond, detail = '') {
  if (cond) { passed++; console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { failed++; console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
}

const hypot = (x, y) => Math.sqrt(x * x + y * y);
const deg = r => r * 180 / Math.PI;

console.log('\nfaster-than-the-wind — recomputing every derived claim\n');

// ───────────────────────────────────────────────────────────────────────────
console.log('[1] Apparent wind on a beam reach — the sail never "runs out"');
// True wind blows toward +x at speed w. Boat sails on a beam reach: heading +y,
// perpendicular to the true wind, at boat speed v. Then:
//   Vaw = Vtw - Vb = (w,0) - (0,v) = (w, -v)
//   |Vaw| = sqrt(w^2 + v^2)          (always > w for any v > 0)
//   angle of apparent wind off the bow: beta = atan(w / v)
// The sailor feels a wind that STRENGTHENS and swings toward the bow as the boat
// speeds up. There is no boat speed at which the apparent wind falls to the true
// wind or vanishes — so crossing "wind speed" is not a kinematic barrier.
const w = 10; // pick any true wind speed
{
  let prevMag = -1, prevBeta = 999;
  let monotoneMag = true, monotoneBeta = true, alwaysStronger = true;
  for (let v = 0.5; v <= 60; v += 0.5) {
    const mag = hypot(w, v);
    const beta = deg(Math.atan2(w, v)); // apparent-wind angle off the bow
    if (mag <= w) alwaysStronger = false;
    if (mag < prevMag - 1e-12) monotoneMag = false;   // |Vaw| increases with v
    if (beta > prevBeta + 1e-12) monotoneBeta = false; // beta decreases with v (swings to bow)
    prevMag = mag; prevBeta = beta;
  }
  check('|Vaw| > true wind for every boat speed v>0', alwaysStronger);
  check('|Vaw| strictly increases with boat speed', monotoneMag);
  check('apparent wind swings toward the bow as boat speeds up', monotoneBeta);
}
// Worked example the page prints: w=10, v=20 -> 22.36 kn, 26.57 deg off the bow.
{
  const v = 20;
  const mag = hypot(w, v), beta = deg(Math.atan2(w, v));
  check('worked example |Vaw|', near(mag, 22.360679, 1e-5), `= ${mag.toFixed(3)} (want 22.361)`);
  check('worked example beta off bow', near(beta, 26.56505, 1e-4), `= ${beta.toFixed(2)}deg (want 26.57)`);
}

// ───────────────────────────────────────────────────────────────────────────
console.log('\n[2] The idealized kinematic ceiling on a beam reach: v/w = cot(beta_min)');
// A sail can produce drive only while the apparent wind stays at least some
// minimum angle beta_min off the bow (its close-hauled / minimum-drag angle).
// On a beam reach drive fails when atan(w/v) = beta_min, i.e.
//   v/w = 1 / tan(beta_min) = cot(beta_min).
// This is a SIMPLIFIED upper bound (it ignores drag magnitude; the real ceiling
// is lower). It is on the page only to show WHY low-drag craft reach several
// times wind speed: a rigid wing pointing ~12 deg gives ~4.7x. The page labels
// it as illustrative, not a measured speed.
for (const betaMin of [30, 20, 15, 12]) {
  const ratio = 1 / Math.tan(betaMin * Math.PI / 180);
  // consistency: at v = ratio*w on a beam reach, the apparent wind angle equals betaMin
  const vAtLimit = ratio * w;
  const betaAtLimit = deg(Math.atan2(w, vAtLimit));
  check(`beta_min=${betaMin}deg -> v/w = ${ratio.toFixed(2)}`, near(betaAtLimit, betaMin, 1e-6));
}
// Sanity: a soft sail (~30 deg) tops out near true wind; a wing (~12 deg) ~ 4.7x.
check('soft sail (30deg) ceiling ~ 1.73x', near(1 / Math.tan(30 * Math.PI / 180), 1.7320508, 1e-6));
check('rigid wing (12deg) ceiling ~ 4.70x', near(1 / Math.tan(12 * Math.PI / 180), 4.7046301, 1e-6));

// ───────────────────────────────────────────────────────────────────────────
console.log('\n[3] Directly downwind: the two demonstrations are one event in two frames');
// Cart runs directly downwind (+x) at ground speed u; the air moves at w (+x).
// Apparent wind on the cart = Vtw - Vb = (w - u). For u > w this is NEGATIVE:
// a HEADWIND of magnitude (u - w) blowing in the crew's face while they travel
// straight downwind. So the cart cannot be "pushed by a tailwind" once u > w.
{
  const wind = 1;                         // normalize true wind to 1
  for (const u of [1.5, 2.0, 2.8, 3.5]) {
    const apparent = wind - u;            // signed, +x = downwind
    const headwind = -apparent;           // magnitude of the headwind felt
    check(`u=${u}w: crew feels a ${headwind.toFixed(1)}w HEADWIND going downwind`,
      apparent < 0 && near(headwind, u - wind));
  }
  // At the NALSA record u = 2.8w the crew faces a 1.8x headwind while dead downwind.
  check('at the 2.8x record: 1.8x headwind in the face', near(2.8 - 1, 1.8));
}
// Frame change into the AIR frame (subtract Vtw = w from every velocity):
//   air:    w - w = 0        (still)
//   ground: 0 - w = -w       (a belt sliding backward at the wind speed)
//   cart:   u - w            (moving FORWARD through still air, if u > w)
// => "directly downwind faster than the wind" (ground frame) is identically
//    "a geared cart rolling forward off a backward-moving treadmill in still
//    air" (air frame). This is the tabletop demo that settled the argument.
{
  const wind = 1, u = 2.8;
  const airFrame = { air: wind - wind, ground: 0 - wind, cart: u - wind };
  check('air frame: air is still', near(airFrame.air, 0));
  check('air frame: ground is a belt at -w', near(airFrame.ground, -wind));
  check('air frame: cart moves forward at (u-w) > 0', airFrame.cart > 0 && near(airFrame.cart, u - wind));
}

// ───────────────────────────────────────────────────────────────────────────
console.log('\n[4] Energy: the source is the air-ground velocity difference, and it is finite');
// This is NOT a perpetual-motion machine. The energy comes from the relative
// motion between two media. In the ground frame the propeller pushes air
// backward (thrust T forward on the cart, force -T on the air). The air moves at
// +w, so the power the machine draws from the air is
//   P_from_air = -(force on air)·(air velocity) = -(-T)(w) = T·w  > 0,
// finite, and PROPORTIONAL TO w. When the wind stops (w = 0) the available power
// is exactly zero: the machine cannot run on nothing. That single fact is the
// whole answer to "isn't this perpetual motion?" — no, it stops when the wind does.
{
  const T = 1; // any positive thrust
  for (const wind of [0, 0.5, 1, 2]) {
    const P = T * wind;
    check(`wind=${wind}: available power = T·w = ${P.toFixed(1)} (zero when wind is zero)`,
      near(P, T * wind) && P >= 0 && (wind === 0 ? P === 0 : P > 0));
  }
}

// ───────────────────────────────────────────────────────────────────────────
console.log('\n[5] Arithmetic of the quoted records (the records themselves are SOURCED, not derived)');
// Blackbird downwind: 27.7 mph in 10 mph wind (NALSA, 2010-07-02).
check('Blackbird downwind 27.7/10 ~ 2.8x', near(27.7 / 10, 2.77, 5e-3), `= ${(27.7 / 10).toFixed(2)}`);
// Blackbird upwind: ~2.1x (NALSA, 2012).
check('Blackbird upwind stated 2.1x is > 1 (against the wind, and faster)', 2.1 > 1);
// Vestas Sailrocket 2: 65.45 kn over 500 m in ~25 kn wind (WSSRC, 2012-11-24).
// Ratio is DERIVED from an approximate wind, so the page states it as "about 2.5x".
check('Sailrocket 65.45/25 ~ 2.6x (approx wind -> approx ratio)', near(65.45 / 25, 2.618, 5e-3), `= ${(65.45 / 25).toFixed(2)}`);
// Greenbird land record: 126.1 mph (Ivanpah, 2009).
check('Greenbird 126.1 mph is the sourced figure (not 126.2)', near(126.1, 126.1));

// ───────────────────────────────────────────────────────────────────────────
console.log('\n[6] General course angle: exceeding true wind is not special to a beam reach');
// For a boat sailing at course angle theta measured from the DOWNWIND direction
// (theta = 90deg is a beam reach, theta -> 0 is dead downwind), at boat speed v:
//   Vb  = v * (cos? ...) — set true wind toward +x; boat heading at angle theta
//   off the +x (downwind) axis: Vb = v*(cos theta, sin theta), Vtw = (w,0).
//   Vaw = (w - v cos theta, -v sin theta).
// Check: on a broad reach (theta = 60deg) a boat can still make |Vaw| >= w and
// keep the apparent wind off the bow, so it too can exceed true wind speed.
{
  const theta = 60 * Math.PI / 180, wind = 10, v = 15; // v>w already
  const vaw = [wind - v * Math.cos(theta), -v * Math.sin(theta)];
  const mag = hypot(vaw[0], vaw[1]);
  check('broad reach (60deg), v=1.5w: apparent wind still >= true wind', mag >= wind, `|Vaw|=${mag.toFixed(2)}`);
}

// ───────────────────────────────────────────────────────────────────────────
console.log(`\n${passed}/${passed + failed} checks passed\n`);
process.exit(failed === 0 ? 0 : 1);
