#!/usr/bin/env node
/* verify.mjs — the geometry behind the stratum
   "The Compression That Isn't the Lens" (/strata/the-compression-that-isnt-the-lens/).

   The claim the page corrects: a telephoto lens is said to "compress" distance and a
   wide-angle lens to "distort" faces. Both effects are real; neither is caused by the
   glass. Perspective — the projected relative sizes of near and far — is a function of
   the VIEWPOINT (camera-to-subject distance) alone. For two equal-sized objects at distances
   d1 and d2 the apparent-size ratio is d2/d1, with NO focal length in it, because the pinhole
   projection gives apparent size = f·(H/Z) and the common f cancels. Focal length only
   sets the angle of view.

   Sources for the asserted numbers:
     • Wikipedia, "Perspective distortion": perspective is set by distance, not the lens;
       a cropped wide frame gives the same content — https://en.wikipedia.org/wiki/Perspective_distortion
     • Wikipedia, "Dolly zoom": Irmin Roberts (Paramount second-unit), Hitchcock's Vertigo
       (1958); the framing rule d = w/(2·tan(½·FOV)) (stated there without an author):
       https://en.wikipedia.org/wiki/Dolly_zoom
     • PetaPixel (2021) and ReefNet/scubageek (2002): 16 mm vs 200 mm from one spot is the
       same picture; "compression" is a distance-and-magnification byproduct.
     • Pinhole camera model: apparent size = f·(H/d); FOV = 2·arctan((sensor/2)/f).

   What this script proves, offline and from scratch:
     1. FOV = 2·arctan((sensor/2)/f) reproduces the angle-of-view figures shown.
     2. The near:far apparent-size ratio equals (d+Δ)/d and is INDEPENDENT of focal length.
     3. Crop-equivalence: the ratio (and every object's projected size ratio) is identical
        whether shot at 16 mm or 200 mm from the same spot.
     4. The dolly-zoom coupling f = 24·d/w (= 8·d for w = 3.0 m) holds the subject at a
        constant 58% of the frame at every distance, while the background magnifies as
        d/(d+Δ), exactly as the distance formula says (the fixed-distance sweep in 2 is what
        rules the lens out).
     5. The symmetric myth: stepping in (small d) exaggerates the ratio, backing up (large d)
        flattens it — both halves ("wide distorts", "tele compresses") are distance effects.
     6. The shipped index.html literally contains the same key figures and attributions.

   run:  node research/the-compression-that-isnt-the-lens/verify.mjs
   No dependencies; node: builtins only. Every number the page displays is recomputed here.
*/
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

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;

// ── scene constants (must match the page) ───────────────────────────────────
const SENS_W = 36, SENS_H = 24;   // full-frame sensor, mm
const DELTA  = 20;                // subject → background separation, m
const HF     = 1.75;              // both figures' height, m
const WFRAME = 3.0;               // locked framing height, m

// ── the geometry (identical to the page's functions) ────────────────────────
const fovH      = (f) => 2 * Math.atan((SENS_W / 2) / f) * 180 / Math.PI;
const fillH     = (f, H, Z) => f * H / (SENS_H * Z);   // fraction of frame height
const ratio     = (d) => (d + DELTA) / d;              // near:far, two equal figures
const lockFocal = (d) => SENS_H * d / WFRAME;          // dolly-zoom coupling: f = 24·d/w
const projSize  = (f, H, Z) => f * H / Z;              // sensor-mm apparent size

// ── 1. Angle of view = 2·arctan((sensor/2)/f) ───────────────────────────────
console.log('\n— angle of view  FOV = 2·arctan(18/f)  (full-frame, horizontal) —');
const fovCases = [
  [16, 96.7], [24, 73.7], [50, 39.6], [85, 23.9], [200, 10.3], [360, 5.7],
];
for (const [f, want] of fovCases) {
  const got = fovH(f);
  ok(`${String(f).padStart(3)} mm → ${got.toFixed(1)}°  (page ${want}°)`,
     approx(got, want, 0.06), `Δ=${(got - want).toFixed(3)}`);
}

// ── 2. near:far ratio = (d+Δ)/d, and it does NOT depend on focal length ──────
console.log('\n— near:far apparent-size ratio = (d+Δ)/d, independent of focal length —');
const ratioCases = [[2, 11.0], [5, 5.0], [8, 3.5], [10, 3.0], [20, 2.0], [40, 1.5]];
for (const [d, want] of ratioCases) {
  ok(`d=${String(d).padStart(2)} m → ratio ${ratio(d).toFixed(2)}× (expect ${want.toFixed(2)})`,
     approx(ratio(d), want, 1e-9));
}
{
  // recompute the ratio the way the page draws it (projected sizes) at both focal extremes
  const d = 8;
  const rWide = projSize(16, HF, d) / projSize(16, HF, d + DELTA);
  const rTele = projSize(360, HF, d) / projSize(360, HF, d + DELTA);
  ok('projected ratio equal at 16 mm and 360 mm (f cancels)',
     approx(rWide, rTele, 1e-12) && approx(rWide, 3.5, 1e-9),
     `16mm=${rWide.toFixed(4)}  360mm=${rTele.toFixed(4)}`);
}

// ── 3. Crop-equivalence: 16 mm cropped to the tele's field = same perspective ─
console.log('\n— crop-equivalence: a 16 mm frame cropped to 200 mm gives the same ratio —');
{
  const d = 8;
  // every object's projected size scales with f by the SAME factor, so cropping
  // (selecting an angular window at the same viewpoint) preserves all size ratios:
  const scale = projSize(200, HF, d) / projSize(16, HF, d); // = 200/16 for any object
  const scaleFar = projSize(200, HF, d + DELTA) / projSize(16, HF, d + DELTA);
  ok('near and far scale by the identical factor 200/16 = 12.5',
     approx(scale, 12.5, 1e-9) && approx(scale, scaleFar, 1e-12),
     `near=${scale.toFixed(3)} far=${scaleFar.toFixed(3)}`);
  ok('therefore the near:far ratio survives the crop unchanged (= 3.50)',
     approx(ratio(d), 3.5, 1e-9));
}

// ── 4. Dolly-zoom coupling holds subject size fixed, background magnifies d/(d+Δ) ─
console.log('\n— dolly zoom: f = 24·d/w (= 8·d for w=3.0 m) pins the subject at 58% —');
for (const d of [2, 5, 8, 20, 40]) {
  const f = lockFocal(d);
  const subj = fillH(f, HF, d);                 // fraction of frame the subject fills
  ok(`d=${String(d).padStart(2)} m → f=${String(Math.round(f)).padStart(3)} mm, subject fills ${(subj*100).toFixed(1)}%`,
     approx(f, 8 * d, 1e-9) && approx(subj, HF / WFRAME, 1e-9),
     `HF/w=${(HF/WFRAME).toFixed(4)}`);
}
{
  const bgMag = (d) => d / (d + DELTA); // background's relative scale under the lock
  ok('with subject pinned, the background still swells: d/(d+Δ) rises 0.111 → 0.333',
     bgMag(2.5) < bgMag(10) && approx(bgMag(2.5), 0.1111, 1e-3) && approx(bgMag(10), 0.3333, 1e-3),
     `d=2.5→${bgMag(2.5).toFixed(3)}  d=10→${bgMag(10).toFixed(3)}`);
  ok('at d=8 the dolly-zoom focal length is 64 mm', approx(lockFocal(8), 64, 1e-9));
}

// ── 5. The check-table snapshot (d = 8 m, three lenses) recomputed exactly ────
console.log('\n— check table snapshot: d = 8 m (far at 28 m) — ratio never moves —');
const tableRows = [
  { f: 24,  fov: 73.7, near: 21.9, far: 6.25 },
  { f: 85,  fov: 23.9, near: 77.5, far: 22.1 },
  { f: 200, fov: 10.3, near: 182,  far: 52.1 },
];
for (const r of tableRows) {
  const near = fillH(r.f, HF, 8) * 100;
  const far  = fillH(r.f, HF, 8 + DELTA) * 100;
  const rat  = near / far;
  const nearOk = approx(Math.round(near * (near < 100 ? 10 : 1)) / (near < 100 ? 10 : 1), r.near, 0.05);
  ok(`${String(r.f).padStart(3)} mm  fov ${fovH(r.f).toFixed(1)}°  near ${near.toFixed(1)}%  far ${far.toFixed(2)}%  ratio ${rat.toFixed(2)}×`,
     approx(fovH(r.f), r.fov, 0.06) && nearOk && approx(far, r.far, 0.05) && approx(rat, 3.5, 1e-9));
}

// ── 6. Symmetric myth: both halves are distance effects ─────────────────────
console.log('\n— both halves of the folk claim are distance effects —');
ok('step in (small d) exaggerates the near:far ratio (wide "distorts")', ratio(2) > ratio(8), `ratio(2)=${ratio(2)} > ratio(8)=${ratio(8)}`);
ok('back up (large d) flattens the near:far ratio (tele "compresses")', ratio(40) < ratio(8), `ratio(40)=${ratio(40)} < ratio(8)=${ratio(8)}`);

// ── 7. The shipped page contains the same figures + attributions ────────────
console.log('\n— shipped index.html parity —');
const here = dirname(fileURLToPath(import.meta.url));
const html = readFileSync(
  join(here, '..', '..', 'public', 'strata', 'the-compression-that-isnt-the-lens', 'index.html'),
  'utf8',
);
const hay = html
  .replace(/&nbsp;/g, ' ')
  .replace(/&thinsp;/g, ' ')
  .replace(/<[^>]+>/g, ' ')
  .replace(/\s+/g, ' ');

const HTML_CHECKS = [
  // attribution / dolly zoom
  'Irmin Roberts', '1958', 'Vertigo', 'Paramount', 'dolly zoom', 'd = w / (2',
  // scene constants
  '36 × 24', 'Δ = 20', '8·d', '58%', 'f·(H/d)',
  // recomputed figures
  '(d + Δ)/d', '3.50', '73.7', '23.9', '10.3', '39.6', '21.9', '6.25', '52.1', '77.5', '182',
  // the sourced quote and the honest boundary
  'distance, not by the lens per se', 'crop',
];
for (const s of HTML_CHECKS) {
  ok(`html contains  "${s}"`, hay.includes(s));
}

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