#!/usr/bin/env node
// Verifier for the portal "The Ruler in the Question".
//
// The portal's load-bearing claim is structural: an apparently factual question
// secretly carries a free parameter the asker never names, so its answer is a
// function answer = f(object, x), and the "rival" answers are just x taking
// different values. Two of the five rungs are NUMERIC and are recomputed here
// from first principles; the three TEXTUAL rungs are verified in their own
// member strata (their verifiers / sourced line-ups), and are re-stated here
// only as internal-consistency assertions so the page's data and this file
// cannot drift apart. Every textual rung is marked [attested] not [computed].
//
// Run: node research/the-ruler-in-the-question/verify.mjs

let pass = 0, fail = 0;
const checks = [];
function ok(name, cond, detail) {
  checks.push([cond ? "PASS" : "FAIL", name, detail || ""]);
  if (cond) pass++; else fail++;
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

// ===========================================================================
// RUNG 1 — x = the reference frame.  "Which mountain is highest?"
//   Three exact, incompatible answers, one per definition of "high".
//   Source figures reproduced from the stratum The Farthest Point (WGS84).
// ===========================================================================
const WGS84_A = 6378137.0;            // semi-major axis (m)
const WGS84_INVF = 298.257223563;     // inverse flattening
const f = 1 / WGS84_INVF;
const e2 = 2 * f - f * f;             // first eccentricity squared

// Geocentric distance to a point at geodetic latitude phi (deg) and
// orthometric height h (m, used as a first approximation of the height along
// the ellipsoid normal — the approximation the source page names explicitly).
function geocentricRadius(latDeg, h) {
  const phi = (latDeg * Math.PI) / 180;
  const sin = Math.sin(phi), cos = Math.cos(phi);
  const N = WGS84_A / Math.sqrt(1 - e2 * sin * sin); // prime-vertical radius
  const X = (N + h) * cos;
  const Z = (N * (1 - e2) + h) * sin;
  return Math.sqrt(X * X + Z * Z);
}

const mountains = {
  Everest:    { lat: 27.988056, elev: 8848.86, baseToPeak: null },
  Chimborazo: { lat: -1.469167, elev: 6263.47, baseToPeak: null },
  MaunaKea:   { lat: 19.820667, elev: 4205,    baseToPeak: 10210 },
};

const rEverest    = geocentricRadius(mountains.Everest.lat,    mountains.Everest.elev);
const rChimborazo = geocentricRadius(mountains.Chimborazo.lat, mountains.Chimborazo.elev);
const dCh = rChimborazo - rEverest;

// (a) sea-level elevation ⇒ Everest wins
ok("R1a frame=sea-level ⇒ Everest highest",
  mountains.Everest.elev > mountains.Chimborazo.elev && mountains.Everest.elev > mountains.MaunaKea.elev,
  `elev: Everest ${mountains.Everest.elev} > Chimborazo ${mountains.Chimborazo.elev} > MaunaKea ${mountains.MaunaKea.elev}`);

// (b) distance from Earth's centre ⇒ Chimborazo wins (the bulge), by ~2.1 km
ok("R1b frame=geocentre ⇒ Chimborazo farthest",
  rChimborazo > rEverest,
  `R: Chimborazo ${(rChimborazo/1000).toFixed(3)} km > Everest ${(rEverest/1000).toFixed(3)} km`);
ok("R1c the geocentric lead matches the published ~2.1 km",
  approx(dCh, 2100, 400),
  `Chimborazo − Everest = ${dCh.toFixed(0)} m (published ≈ 2,072 m / 2.1 km)`);
ok("R1d Chimborazo summit radius ≈ 6,384 km",
  approx(rChimborazo / 1000, 6384.4, 1.0),
  `${(rChimborazo / 1000).toFixed(2)} km`);

// (c) base-to-peak ⇒ Mauna Kea wins (taller than Everest's sea-level height)
ok("R1e frame=base-to-peak ⇒ Mauna Kea tallest [attested 10,210 m from sea floor]",
  mountains.MaunaKea.baseToPeak > mountains.Everest.elev,
  `Mauna Kea ${mountains.MaunaKea.baseToPeak} m base-to-peak > Everest ${mountains.Everest.elev} m elevation`);

// The point of the rung: ONE mountain set, THREE definitions, THREE winners.
const winners = new Set(["Everest", "Chimborazo", "MaunaKea"]);
ok("R1f three different definitions ⇒ three different winners (no overlap)",
  winners.size === 3, "Everest / Chimborazo / Mauna Kea");

// ===========================================================================
// RUNG 2 — x = the ruler's resolution.  "How long is the coast?"
//   Length is not a property of the curve; it is a property of (curve, ruler).
//   The invariant that survives is the fractal dimension D, read off the
//   log-log slope (= 1 − D).  Checked on the Koch curve, whose dimension is
//   known exactly: D = log4 / log3 = 1.261859...
// ===========================================================================
const D_KOCH = Math.log(4) / Math.log(3);

// Build the Koch curve to depth k as a polyline of points in [0,1]x[...].
function kochPoints(depth) {
  let pts = [[0, 0], [1, 0]];
  for (let d = 0; d < depth; d++) {
    const next = [pts[0]];
    for (let i = 0; i < pts.length - 1; i++) {
      const [ax, ay] = pts[i], [bx, by] = pts[i + 1];
      const dx = bx - ax, dy = by - ay;
      const p1 = [ax + dx / 3, ay + dy / 3];
      const p2 = [ax + 2 * dx / 3, ay + 2 * dy / 3];
      // apex of the outward equilateral bump
      const mx = ax + dx / 2, my = ay + dy / 2;
      const nx = -dy, ny = dx; // normal
      const nlen = Math.sqrt(nx * nx + ny * ny);
      const bump = (Math.sqrt(3) / 6) * Math.sqrt(dx * dx + dy * dy);
      const apex = [mx + (nx / nlen) * bump, my + (ny / nlen) * bump];
      next.push(p1, apex, p2, pts[i + 1]);
    }
    pts = next;
  }
  return pts;
}

// Polyline length: sum the segment lengths of a polyline.
function polylineLength(pts) {
  let L = 0;
  for (let i = 0; i < pts.length - 1; i++) {
    const dx = pts[i + 1][0] - pts[i][0], dy = pts[i + 1][1] - pts[i][1];
    L += Math.sqrt(dx * dx + dy * dy);
  }
  return L;
}

// Measure the SAME curve at successively finer resolutions. At refinement
// depth k the prefractal is a polyline of 4^k segments each of length 3^-k,
// so the effective ruler is ε_k = 3^-k and the measured length is its
// polyline length — recomputed here from the generated curve, not assumed.
// This is the structured-walk measurement (Richardson) for a self-similar
// generator; it gives the dimension exactly, with no compass-discretisation
// artefact. (A greedy physical divider undershoots slightly — the same class
// of artefact the coastline page names for its circle control.)
const epsList = [];
const lengths = [];
for (let k = 1; k <= 6; k++) {
  epsList.push(Math.pow(1 / 3, k));         // ε_k = longest segment at depth k
  lengths.push(polylineLength(kochPoints(k)));
}

// length grows monotonically as the ruler shrinks
let monotone = true;
for (let i = 1; i < lengths.length; i++) if (!(lengths[i] > lengths[i - 1] - 1e-12)) monotone = false;
ok("R2a measured length grows as the ruler shrinks",
  monotone,
  epsList.map((e, i) => `ε=${e.toFixed(4)}→L=${lengths[i].toFixed(3)}`).join("  "));

// slope of log L vs log eps  ⇒  D = 1 − slope
function slope(xs, ys) {
  const n = xs.length, mx = xs.reduce((a, b) => a + b) / n, my = ys.reduce((a, b) => a + b) / n;
  let sxy = 0, sxx = 0;
  for (let i = 0; i < n; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sxx += (xs[i] - mx) * (xs[i] - mx); }
  return sxy / sxx;
}
const logEps = epsList.map(Math.log), logLen = lengths.map(Math.log);
const s = slope(logEps, logLen);
const D_measured = 1 - s;
ok("R2b recovered dimension D matches Koch's exact log4/log3",
  approx(D_measured, D_KOCH, 0.02),
  `D_measured = ${D_measured.toFixed(4)}  vs exact ${D_KOCH.toFixed(4)}`);
ok("R2c D > 1 ⇒ length is unbounded, not a single number",
  D_measured > 1.0,
  `D = ${D_measured.toFixed(4)} > 1`);

// ===========================================================================
// RUNG 3 — x = the vocalization of an unpointed script.  Exodus 34:29.
//   The consonantal root ק־ר־נ (q-r-n) is read two exact ways.
//   [attested] — sourced in the stratum The Horns of Moses (BDB 1906).
// ===========================================================================
const qrn = { consonants: "קרנ", asVerb: "qāran — shone / sent out rays", asNoun: "qeren — horn" };
ok("R3a one consonantal root, two exact readings [attested: BDB; The Horns of Moses]",
  qrn.asVerb.includes("shone") && qrn.asNoun.includes("horn") && qrn.consonants.length === 3,
  `${qrn.consonants}: {${qrn.asVerb}} vs {${qrn.asNoun}}`);
ok("R3b the record-correction (LXX read 'glorified', not 'horn') is preserved [attested]",
  true, "the horn enters in Jerome's Vulgate (cornuta), not the Septuagint (dedoxastai)");

// ===========================================================================
// RUNG 4 — x = the target language's lexical grid.  Isaiah 7:14.
//   Hebrew ʿalmâ ('young woman') is broad; Greek narrows it to parthenos.
//   [attested] — sourced in the stratum The Sign of Immanuel.
// ===========================================================================
const almah = { hebrew: "ʿalmâ — young woman (broad)", betulah: "bᵉṯûlâ — specifically 'virgin' (NOT used here)", greek: "parthenos — narrowed" };
ok("R4a the broad source word, the unused specific word, and the narrowed target [attested]",
  almah.hebrew.includes("young woman") && almah.betulah.includes("NOT used") && almah.greek.includes("narrowed"),
  "Hebrew left it open; Greek picked a point inside the range");
ok("R4b honest scope: 'virgin' is narrower than ʿalmâ, not its opposite [attested]",
  true, "no passage proves ʿalmâ means 'non-virgin'; the claim is held to exactly that");

// ===========================================================================
// RUNG 5 — x = the grammar's obligatory evidential.  "It rained."
//   English may assert sourcelessly; ~1/4 of languages may not.
//   [attested] — sourced in the stratum How You Know (Aikhenvald; Barnes 1984).
// ===========================================================================
const evidential = { english: "sourceless assertion permitted", tuyuca: 5, claim: "every finite verb must mark how you know" };
ok("R5a English allows a sourceless assertion; an evidential grammar forbids it [attested]",
  evidential.english.includes("permitted") && evidential.tuyuca >= 4,
  `Tuyuca past tense distinguishes ${evidential.tuyuca} sources of knowledge`);
ok("R5b the same proposition carries different obligatory content under each grammar [attested]",
  true, "'it rained' alone (English) vs 'it rained' + evidential, by law (Tuyuca/Tariana)");

// ===========================================================================
// RUNG 6 (the pure-convention pole) — x = the grouping convention.
//   "How many continents?"  No fact of nature fixes the count; each model is
//   internally exact. The count = the number of DISTINCT groups a model sorts
//   the seven base regions into — computed here, not asserted, the same way
//   the live page computes it, and matching the stratum How Many Continents?.
//   Base regions: N S(America) E(urope) A(sia) F(rica) O(ceania) T (Antarctica).
// ===========================================================================
const contModels = {
  seven:          { N: "N",  S: "S",  E: "E",  A: "A",  F: "F",  O: "O", T: "T"  },
  "six-eurasia":  { N: "N",  S: "S",  E: "EA", A: "EA", F: "F",  O: "O", T: "T"  },
  "six-americas": { N: "AM", S: "AM", E: "E",  A: "A",  F: "F",  O: "O", T: "T"  },
  five:           { N: "AM", S: "AM", E: "E",  A: "A",  F: "F",  O: "O", T: null },
  four:           { N: "AM", S: "AM", E: "AE", A: "AE", F: "AE", O: "O", T: "T"  },
};
const countGroups = (m) => new Set(Object.values(m).filter((g) => g !== null)).size;
const contExpect = { seven: 7, "six-eurasia": 6, "six-americas": 6, five: 5, four: 4 };
for (const k of Object.keys(contModels)) {
  ok(`R6 continents: ${k} model counts ${contExpect[k]} [computed from grouping]`,
    countGroups(contModels[k]) === contExpect[k],
    `${k} → ${countGroups(contModels[k])} distinct groups`);
}
ok("R6 the count ranges over {4,5,6,7}, no fact of nature settling it [pure convention]",
  JSON.stringify([...new Set(Object.values(contExpect))].sort((a, b) => a - b)) === JSON.stringify([4, 5, 6, 7]),
  "four classroom conventions, four internally-exact counts");

// ===========================================================================
// THE GRADIENT — why naming the ruler is NOT relativism. Each rung sits at a
// known hardness of floor beneath the convention; the partition is the page's
// load-bearing anti-relativist claim, asserted here as structure.
// ===========================================================================
const gradient = [
  { rung: "continents", floor: "none",      note: "pure convention — no fact of nature fixes the count" },
  { rung: "mountain",   floor: "facts",     note: "convention selects among three exact measured heights" },
  { rung: "coast",      floor: "invariant", note: "length is soft, but the dimension D is convention-independent" },
];
ok("GRADIENT three distinct hardnesses of floor (none / facts / invariant)",
  new Set(gradient.map((g) => g.floor)).size === 3,
  gradient.map((g) => `${g.rung}:${g.floor}`).join("  "));
ok("GRADIENT the coast's invariant D>1 is real even though its length is not",
  D_measured > 1.0,
  `D = ${D_measured.toFixed(4)} survives every ruler; the length does not`);

// ===========================================================================
// THE SPINE — the schema answer = f(object, x) holds at every rung.
// ===========================================================================
const rungs = [
  { name: "frame",          object: "the Earth",        x: "which datum 'high' means",        kind: "computed" },
  { name: "ruler",          object: "a coastline",      x: "the ruler's resolution",          kind: "computed" },
  { name: "vocalization",   object: "ק־ר־נ",            x: "which vowels the reader supplies", kind: "attested" },
  { name: "lexical grid",   object: "ʿalmâ",            x: "which language you translate into", kind: "attested" },
  { name: "evidential",     object: "'it rained'",      x: "which grammar you must speak in",  kind: "attested" },
  { name: "grouping",       object: "the land",         x: "which convention cuts it",        kind: "computed" },
];
ok("SPINE all six rungs instantiate answer = f(object, x)",
  rungs.length === 6 && rungs.every(r => r.object && r.x),
  "6 rungs: 3 computed here, 3 attested in their member strata");
ok("SPINE the ladder runs physical → linguistic across two venues (P1 → P6), plus the pure-convention pole",
  rungs[0].kind === "computed" && rungs[4].kind === "attested" && rungs[5].kind === "computed",
  "rungs 1–2 Verification Venue (P1); rungs 3–5 Translation-Criticism Venue (P6); rung 6 the off-ladder convention pole");

// ===========================================================================
console.log("\nThe Ruler in the Question — verifier\n" + "=".repeat(52));
for (const [st, name, detail] of checks) {
  console.log(`${st === "PASS" ? "  ✓" : "  ✗"} ${name}${detail ? "\n      " + detail : ""}`);
}
console.log("=".repeat(52));
console.log(`${pass} / ${pass + fail} PASS` + (fail ? `  — ${fail} FAILED` : ""));
process.exit(fail ? 1 : 0);
