#!/usr/bin/env node
// Verifier for "The Mediant" — the Stern–Brocot tree as a navigable musical
// instrument (Number seam). Promotes deposition dep:1780702946039:00oy9jxw.
//
// Every claim the stratum makes is recomputed here from scratch, with exact
// BigInt arithmetic for the tree (no floating point in the enumeration). Run:
//   node research/the-mediant/verify.mjs
// Exit 0 iff every check passes. The three CORRECTIONS to the deposition are
// marked [CORRECTION]; the gate did real work on them.

let pass = 0, fail = 0;
const out = [];
function check(label, cond, detail = '') {
  if (cond) { pass++; out.push(`  ok   ${label}${detail ? '  — ' + detail : ''}`); }
  else { fail++; out.push(`  FAIL ${label}${detail ? '  — ' + detail : ''}`); }
}
function section(t) { out.push(`\n== ${t} ==`); }

// ---------------------------------------------------------------------------
// Exact rational helpers (BigInt)
const gcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; };
// A node is {p, q} in lowest terms (BigInt). Mediant of a/b and c/d = (a+c)/(b+d).
const mediant = (l, r) => ({ p: l.p + r.p, q: l.q + r.q });

// Build the Stern–Brocot tree by binary path. Path is a string of 'L'/'R'.
// Boundaries start at 0/1 (left) and 1/0 (right, = +infinity).
function nodeForPath(path) {
  let L = { p: 0n, q: 1n }, R = { p: 1n, q: 0n };
  let node = mediant(L, R); // 1/1, the root (empty path)
  for (const ch of path) {
    if (ch === 'L') { R = node; }
    else { L = node; }
    node = mediant(L, R);
  }
  return { node, L, R };
}

// ---------------------------------------------------------------------------
section('1 · Every node is already in lowest terms (unimodular invariant bc−ad=1)');
{
  // The two bounding ancestors of every node satisfy the Farey/unimodular
  // relation b·c − a·d = 1, which forces their mediant into lowest terms.
  let allUnimodular = true, allReduced = true, worst = '';
  function walk(L, R, depth) {
    if (depth > 14) return;
    const det = L.q * R.p - L.p * R.q; // b*c - a*d for L=a/b, R=c/d
    if (det !== 1n) { allUnimodular = false; worst = `det=${det} at depth ${depth}`; }
    const m = mediant(L, R);
    if (gcd(m.p, m.q) !== 1n) { allReduced = false; }
    walk(L, m, depth + 1);
    walk(m, R, depth + 1);
  }
  walk({ p: 0n, q: 1n }, { p: 1n, q: 0n }, 0);
  check('bc − ad = 1 holds at every node (to depth 14)', allUnimodular, worst || 'invariant held');
  check('every mediant is automatically in lowest terms', allReduced);
}

// ---------------------------------------------------------------------------
section('2 · Bijection: every positive rational appears exactly once (to depth 18)');
{
  const seen = new Map(); // "p/q" -> path
  let dup = false, dupInfo = '';
  function enumerate(L, R, path, depth) {
    if (depth > 18) return;
    const m = mediant(L, R);
    const key = `${m.p}/${m.q}`;
    if (seen.has(key)) { dup = true; dupInfo = `${key} at '${path}' and '${seen.get(key)}'`; }
    else seen.set(key, path);
    enumerate(L, m, path + 'L', depth + 1);
    enumerate(m, R, path + 'R', depth + 1);
  }
  enumerate({ p: 0n, q: 1n }, { p: 1n, q: 0n }, '', 0);
  check('no rational appears twice in the tree (depth ≤ 18)', !dup, dupInfo || `${seen.size} distinct nodes, all unique`);

  // Surjectivity (depth-independent): every reduced p/q with p,q ≤ 40 is
  // reachable — found by mediant binary search, which terminates exactly on it.
  function reachable(P, Q) {
    const Pb = BigInt(P), Qb = BigInt(Q);
    let L = { p: 0n, q: 1n }, R = { p: 1n, q: 0n }, m = mediant(L, R), s = 0;
    while (!(m.p === Pb && m.q === Qb)) {
      if (m.p * Qb - Pb * m.q < 0n) L = m; else R = m;
      m = mediant(L, R);
      if (++s > 2000) return false;
    }
    return true;
  }
  let missing = '';
  for (let p = 1; p <= 40 && !missing; p++) {
    for (let q = 1; q <= 40; q++) {
      if (gcd(BigInt(p), BigInt(q)) !== 1n) continue;
      if (!reachable(p, q)) { missing = `${p}/${q}`; break; }
    }
  }
  check('every reduced p/q with p,q ≤ 40 is reachable (by mediant search)', missing === '', missing ? `missing ${missing}` : 'all present');
}

// ---------------------------------------------------------------------------
section('3 · Path ↔ continued fraction (the path is a binary search by mediants)');
{
  // Find the L/R path to a target rational p/q by mediant binary search,
  // then check it reconstructs p/q exactly and matches the run-length =
  // continued-fraction reading.
  function pathTo(P, Q) {
    const Pb = BigInt(P), Qb = BigInt(Q);
    let L = { p: 0n, q: 1n }, R = { p: 1n, q: 0n };
    let m = mediant(L, R), path = '';
    // compare m vs P/Q via cross-multiplication (exact)
    const cmp = (a) => a.p * Qb - Pb * a.q; // <0 means a < P/Q
    while (!(m.p === BigInt(P) && m.q === BigInt(Q))) {
      if (cmp(m) < 0n) { L = m; path += 'R'; } // m too small → go right
      else { R = m; path += 'L'; }            // m too big → go left
      m = mediant(L, R);
      if (path.length > 200) break;
    }
    return path;
  }
  // Continued fraction of P/Q (positive). Returns partial quotients [a0,a1,...].
  function cf(P, Q) {
    const a = []; let x = P, y = Q;
    while (y !== 0) { a.push(Math.floor(x / y)); [x, y] = [y, x % y]; }
    return a;
  }
  // The path's run-lengths (starting with R-run) should equal the CF, with the
  // standard fencepost adjustment: a0 R's, a1 L's, a2 R's, ..., last quotient −1.
  function runLengths(path) {
    if (path === '') return [];
    const runs = []; let cur = path[0], n = 0;
    for (const ch of path) { if (ch === cur) n++; else { runs.push(n); cur = ch; n = 1; } }
    runs.push(n);
    return { first: path[0], runs };
  }
  for (const [P, Q] of [[3, 2], [4, 3], [5, 4], [7, 5], [22, 7], [355, 113]]) {
    const path = pathTo(P, Q);
    const { node } = nodeForPath(path);
    const reconstructs = node.p === BigInt(P) && node.q === BigInt(Q);
    check(`path to ${P}/${Q} reconstructs ${P}/${Q}`, reconstructs, `path='${path}'`);
    // CF run-length correspondence
    const a = cf(P, Q);                          // e.g. 355/113 = [3;7,16]
    const { first, runs } = runLengths(path);
    // Expected runs: a0, a1, ..., a_{k-1}, a_k - 1  (first run is R iff a0>=1, i.e. value>1)
    const exp = a.slice();
    exp[exp.length - 1] -= 1;
    while (exp.length && exp[exp.length - 1] === 0) exp.pop();
    const runsMatch = JSON.stringify(runs) === JSON.stringify(exp);
    check(`run-lengths of path to ${P}/${Q} = continued fraction ${JSON.stringify(a)}`, runsMatch,
      `runs=${JSON.stringify(runs)} starting '${first}', expected ${JSON.stringify(exp)}`);
  }
}

// ---------------------------------------------------------------------------
section('4 · Cents and named intervals (1200·log2(p/q)), and their TRUE depths');
{
  const cents = (p, q) => 1200 * Math.log2(p / q);
  const round = (x) => Math.round(x);
  // depth = number of edges from the root 1/1 (root at depth 0)
  function depthOf(P, Q) {
    let L = { p: 0n, q: 1n }, R = { p: 1n, q: 0n }, m = mediant(L, R), d = 0;
    while (!(m.p === BigInt(P) && m.q === BigInt(Q))) {
      if (m.p * BigInt(Q) - BigInt(P) * m.q < 0n) L = m; else R = m;
      m = mediant(L, R); d++;
      if (d > 500) break;
    }
    return d;
  }
  // [name, p, q, expected rounded cents, expected depth (root=0)]
  const intervals = [
    ['unison', 1, 1, 0, 0],
    ['octave', 2, 1, 1200, 1],
    ['perfect fifth', 3, 2, 702, 2],
    ['perfect fourth', 4, 3, 498, 3],   // [CORRECTION] deposition implied depth ≤2
    ['major sixth', 5, 3, 884, 3],
    ['major third', 5, 4, 386, 4],      // [CORRECTION] deposition said depth 3
    ['minor third', 6, 5, 316, 5],
    ['septimal minor third', 7, 6, 267, 6],
    ['major second', 9, 8, 204, 8],     // CF [1;8] → R then 7 L's — a deep node despite being a common interval
  ];
  for (const [name, p, q, ec, ed] of intervals) {
    check(`${name} ${p}/${q} = ${ec}¢`, round(cents(p, q)) === ec, `${cents(p, q).toFixed(2)}¢`);
    check(`${name} ${p}/${q} sits at depth ${ed} (root=0)`, depthOf(p, q) === ed, `computed depth ${depthOf(p, q)}`);
  }
}

// ---------------------------------------------------------------------------
section('5 · [CORRECTION] The equal-temperament fifth is 700¢, not 702¢');
{
  // Deposition text: "Walk toward ... the equal-temperament fifth, 2^(7/12) ...
  // The melody approaches 702 cents." The ET fifth is exactly 700¢ by
  // definition (7 semitones × 100¢). 702¢ (701.955) is the JUST fifth 3/2.
  const etFifthCents = 1200 * Math.log2(Math.pow(2, 7 / 12)); // = 700 exactly
  const justFifthCents = 1200 * Math.log2(3 / 2);              // = 701.955...
  check('2^(7/12) is exactly 700¢ (ET fifth)', Math.abs(etFifthCents - 700) < 1e-9, etFifthCents.toFixed(6));
  check('3/2 is 701.955¢ (just fifth ≈ 702¢, the value the deposition mis-assigned to ET)',
    Math.round(justFifthCents) === 702, justFifthCents.toFixed(4));
  check('the two differ by the syntonic-comma-scale ~1.955¢ (so 700 ≠ 702 is real, not rounding)',
    Math.abs(justFifthCents - etFifthCents - 1.955) < 0.01, (justFifthCents - etFifthCents).toFixed(4) + '¢');
  // 2^(7/12) ≈ 1.4983 (deposition's decimal is right; only the cents label was wrong)
  check("deposition's decimal 2^(7/12) ≈ 1.4983 is correct", Math.abs(Math.pow(2, 7 / 12) - 1.4983) < 5e-4, Math.pow(2, 7 / 12).toFixed(6));
}

// ---------------------------------------------------------------------------
section('6 · One-sided best approximation (the simplest fraction strictly between bounds)');
{
  // On the path toward a target, each node is the UNIQUE fraction of smallest
  // denominator strictly between its two bounding ancestors. We verify: no
  // fraction with denominator ≤ node.q lies strictly between L and R except the
  // node itself. (This is the precise, one-sided sense of "best approximation".)
  function pathBounds(P, Q, steps) {
    let L = { p: 0n, q: 1n }, R = { p: 1n, q: 0n }, m = mediant(L, R), s = 0;
    const trace = [];
    while (!(m.p === BigInt(P) && m.q === BigInt(Q)) && s < steps) {
      trace.push({ L: { ...L }, R: { ...R }, m: { ...m } });
      if (m.p * BigInt(Q) - BigInt(P) * m.q < 0n) L = m; else R = m;
      m = mediant(L, R); s++;
    }
    return trace;
  }
  // toward the just fifth 3/2 region — use a deep irrational-ish target (the ET
  // fifth) so the path is long; check the simplicity property on each node.
  const Pn = 442, Qn = 295; // 442/295 ≈ 1.49831 — a good rational stand-in for 2^(7/12)
  const trace = pathBounds(Pn, Qn, 12);
  let simplest = true, ce = '';
  for (const { L, R, m } of trace) {
    const lo = Number(L.p) / Number(L.q), hi = Number(R.p) / Number(R.q);
    const a = Math.min(lo, hi), b = Math.max(lo, hi);
    const mq = Number(m.q);
    // is there any fraction j/k strictly inside (a,b) with k < mq? there must not be.
    let found = false;
    for (let k = 1; k < mq && !found; k++) {
      const jmin = Math.floor(a * k) + 1, jmax = Math.ceil(b * k) - 1;
      for (let j = jmin; j <= jmax; j++) {
        const v = j / k;
        if (v > a && v < b) { found = true; break; }
      }
    }
    if (found) { simplest = false; ce = `${m.p}/${m.q}`; }
  }
  check('each path node is the smallest-denominator fraction between its bounds', simplest, ce ? `counterexample near ${ce}` : `checked ${trace.length} nodes`);
}

// ---------------------------------------------------------------------------
section('7 · Instrument arithmetic matches (frequency = 220·p/q, cents, sibling preview)');
{
  // Mirrors exactly what public/strata/the-mediant/index.html computes.
  const F0 = 220;
  const freq = (p, q) => F0 * p / q;
  const cents = (p, q) => Math.round(1200 * Math.log2(p / q));
  check('root 1/1 → 220 Hz, 0¢', freq(1, 1) === 220 && cents(1, 1) === 0);
  check('octave 2/1 → 440 Hz, 1200¢', freq(2, 1) === 440 && cents(2, 1) === 1200);
  check('fifth 3/2 → 330 Hz, 702¢', freq(3, 2) === 330 && cents(3, 2) === 702);
  // children of the root are 1/2 (lower octave) and 2/1 (octave): exact mediants
  const { node } = nodeForPath('');
  const lc = mediant({ p: 0n, q: 1n }, node);  // mediant(0/1, 1/1) = 1/2
  const rc = mediant(node, { p: 1n, q: 0n });  // mediant(1/1, 1/0) = 2/1
  check('left child of root = 1/2, right child = 2/1', lc.p === 1n && lc.q === 2n && rc.p === 2n && rc.q === 1n);
}

// ---------------------------------------------------------------------------
console.log('# The Mediant — verification\n');
console.log(out.join('\n'));
console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
