// Before the Rabbits — offline verifier for the combinatorics of Sanskrit
// moraic (mātrā) meter, and its identity with the Fibonacci numbers.
//
// The historical record-correction the stratum makes is checked by humans and
// sources (see the page's apparatus); what THIS file checks is the one thing a
// machine can settle beyond dispute: the *counting*. Everything the page asserts
// about how many rhythms there are, the recurrence, the Pascal-diagonal bridge,
// and the closed form is recomputed here from a brute-force enumeration — never
// trusted to a formula — and written to artifact.json, which the page then
// displays. If the page and the artifact drift, the drift guard fails.
//
// The object. A line of mātrā ("moraic") verse is a sequence of syllables, each
// either LAGHU (light/short, written •, worth 1 mora) or GURU (heavy/long,
// written —, worth 2 morae). A "mātrā-vṛtta of n morae" is any such sequence
// whose morae sum to exactly n. We count them.
//
//   • brute-force enumeration of every laghu/guru sequence summing to n morae;
//   • the count is F(n+1) (Fibonacci, F(1)=F(2)=1) — the result Virahāṅka,
//     Gopāla and Hemacandra were after;
//   • the recurrence count(n)=count(n−1)+count(n−2) holds, AND the bijection
//     behind it is exhibited explicitly (every n-mora rhythm ends in a laghu
//     atop an (n−1)-rhythm, or a guru atop an (n−2)-rhythm — disjoint, exhaustive);
//   • the Pascal bridge: the number of n-mora rhythms with exactly k GURU is the
//     binomial coefficient C(n−k, k); summing over k gives the count — i.e. the
//     Fibonacci numbers are the shallow diagonals of Pingala's meru-prastāra
//     (Pascal's triangle). This is the honest link from Pingala's binomial tools
//     to the Fibonacci result he did not himself state.
//   • the closed form (Binet) agrees with the enumeration.
//
// Run:  node research/before-the-rabbits/verify.mjs
"use strict";
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const here = dirname(fileURLToPath(import.meta.url));

const checks = [];
let id = 0;
function check(name, pass, detail) {
  id++;
  checks.push({ n: id, name, pass: !!pass, detail });
  if (!pass) console.error(`  ✗ [${id}] ${name} — ${detail}`);
}

// ───────────────────────────────────────────────────────────────────────────
// 1. ENUMERATE. Generate, by brute force, every sequence of L (1 mora) and
//    G (2 morae) summing to exactly n morae. We return them as strings of
//    "L"/"G" so the page can display the actual rhythms for small n.
function enumerate(n) {
  const out = [];
  (function rec(rem, acc) {
    if (rem === 0) { out.push(acc); return; }
    rec(rem - 1, acc + "L");            // place a laghu (1 mora)
    if (rem >= 2) rec(rem - 2, acc + "G"); // place a guru (2 morae)
  })(n, "");
  return out;
}

const N = 16;                       // compute morae-counts 0..N
const seqs = [];                    // seqs[n] = array of rhythm strings
for (let n = 0; n <= N; n++) seqs.push(enumerate(n));
const count = seqs.map((s) => s.length);

// sanity: every enumerated rhythm really sums to n, and they are distinct
for (let n = 0; n <= N; n++) {
  const morae = (s) => [...s].reduce((a, c) => a + (c === "G" ? 2 : 1), 0);
  const allSum = seqs[n].every((s) => morae(s) === n);
  const distinct = new Set(seqs[n]).size === seqs[n].length;
  check(`n=${n}: every enumerated rhythm sums to ${n} morae`, allSum, "a sequence summed wrong");
  check(`n=${n}: enumerated rhythms are distinct`, distinct, "duplicate rhythm produced");
}

// ───────────────────────────────────────────────────────────────────────────
// 2. FIBONACCI. F(1)=F(2)=1, F(k)=F(k-1)+F(k-2). count(n) should equal F(n+1).
const F = [0n, 1n, 1n];
for (let k = 3; k <= N + 2; k++) F.push(F[k - 1] + F[k - 2]);

for (let n = 0; n <= N; n++) {
  const expected = F[n + 1];
  check(
    `count(${n} morae) = F(${n + 1}) = ${expected}`,
    BigInt(count[n]) === expected,
    `enumeration gave ${count[n]}, Fibonacci gives ${expected}`,
  );
}
// the visible sequence the page prints (morae 1..10 → 1,2,3,5,8,13,21,34,55,89)
const visibleSeq = count.slice(1, 11);
check(
  "morae 1..10 give 1,2,3,5,8,13,21,34,55,89 (the numbers Gopāla & Hemacandra listed)",
  JSON.stringify(visibleSeq) === JSON.stringify([1, 2, 3, 5, 8, 13, 21, 34, 55, 89]),
  `got ${visibleSeq.join(",")}`,
);

// ───────────────────────────────────────────────────────────────────────────
// 3. RECURRENCE + BIJECTION. The proof Virahāṅka/Hemacandra gave: a rhythm of n
//    morae either ends in a laghu (strip it → a rhythm of n−1) or ends in a guru
//    (strip it → a rhythm of n−2). The two cases are disjoint and exhaustive, so
//    count(n)=count(n−1)+count(n−2). We don't assert it — we BUILD the two maps
//    and check they are bijections onto seqs[n−1] and seqs[n−2].
for (let n = 2; n <= N; n++) {
  const endsL = seqs[n].filter((s) => s.endsWith("L"));
  const endsG = seqs[n].filter((s) => s.endsWith("G"));
  check(`n=${n}: the two endings partition the rhythms`, endsL.length + endsG.length === count[n], "partition leaked");
  // stripping the final laghu is a bijection onto the (n−1)-rhythms
  const stripL = new Set(endsL.map((s) => s.slice(0, -1)));
  const ok1 = stripL.size === endsL.length &&
    endsL.length === count[n - 1] &&
    [...stripL].every((s) => seqs[n - 1].includes(s));
  check(`n=${n}: drop final laghu ⇄ rhythms of ${n - 1} morae (bijection)`, ok1, "not a clean bijection to n−1");
  // stripping the final guru is a bijection onto the (n−2)-rhythms
  const stripG = new Set(endsG.map((s) => s.slice(0, -1)));
  const ok2 = stripG.size === endsG.length &&
    endsG.length === count[n - 2] &&
    [...stripG].every((s) => seqs[n - 2].includes(s));
  check(`n=${n}: drop final guru ⇄ rhythms of ${n - 2} morae (bijection)`, ok2, "not a clean bijection to n−2");
}

// ───────────────────────────────────────────────────────────────────────────
// 4. PASCAL BRIDGE. The number of n-mora rhythms with exactly k GURU (heavy)
//    syllables: a rhythm with k gurus and (n−2k) laghus has (n−k) syllables in
//    total, and we choose which k of them are heavy → C(n−k, k). Summing over k
//    gives the count. So the Fibonacci numbers are the shallow ("rising")
//    diagonals of Pascal's triangle — the meru-prastāra Pingala's tradition
//    tabulated. We verify C(n−k,k) against the *enumeration* (count rhythms by
//    their number of G's), not against itself.
function binom(a, b) {
  if (b < 0 || b > a) return 0n;
  let r = 1n;
  for (let i = 0; i < b; i++) r = (r * BigInt(a - i)) / BigInt(i + 1);
  return r;
}
const diagonals = [];               // diagonals[n] = [C(n,0),C(n-1,1),...]
for (let n = 0; n <= N; n++) {
  // enumerated: tally rhythms of n morae by guru-count k
  const byK = {};
  for (const s of seqs[n]) {
    const k = [...s].filter((c) => c === "G").length;
    byK[k] = (byK[k] || 0) + 1;
  }
  const row = [];
  let sum = 0n;
  for (let k = 0; 2 * k <= n; k++) {
    const b = binom(n - k, k);
    row.push(Number(b));
    sum += b;
    check(
      `n=${n}, k=${k} gurus: enumerated ${byK[k] || 0} = C(${n - k},${k}) = ${b}`,
      BigInt(byK[k] || 0) === b,
      `enumeration ${byK[k] || 0} ≠ binomial ${b}`,
    );
  }
  diagonals.push(row);
  check(
    `n=${n}: Σ_k C(n−k,k) = F(${n + 1}) (Fibonacci is a Pascal diagonal)`,
    sum === F[n + 1],
    `diagonal sum ${sum} ≠ F(${n + 1})=${F[n + 1]}`,
  );
}

// ───────────────────────────────────────────────────────────────────────────
// 5. CLOSED FORM (Binet). count(n) = F(n+1) = round(φ^(n+1)/√5), φ=(1+√5)/2.
//    Checked for n where doubles stay exact (F up to ~2^52).
const phi = (1 + Math.sqrt(5)) / 2;
for (let n = 0; n <= 12; n++) {
  const binet = Math.round(Math.pow(phi, n + 1) / Math.sqrt(5));
  check(`n=${n}: Binet round(φ^${n + 1}/√5) = ${count[n]}`, binet === count[n], `Binet gave ${binet}`);
}

// ───────────────────────────────────────────────────────────────────────────
// 6. HEMACANDRA'S ARRAY (mātrāmeru) built purely additively, as he described it
//    — "the sum of the last and the one before the last" — must reproduce the
//    same numbers the enumeration produced. Start 1,2 (morae 1 and 2).
const hema = [1, 2];
while (hema.length < 10) hema.push(hema[hema.length - 1] + hema[hema.length - 2]);
check(
  "Hemacandra's purely-additive array reproduces the enumerated counts (morae 1..10)",
  JSON.stringify(hema) === JSON.stringify(visibleSeq),
  `additive array ${hema.join(",")} ≠ enumeration ${visibleSeq.join(",")}`,
);

// ───────────────────────────────────────────────────────────────────────────
// WRITE ARTIFACT. The page imports these numbers; the drift guard re-checks them.
const artifact = {
  generatedBy: "research/before-the-rabbits/verify.mjs",
  note: "Counts of Sanskrit moraic (mātrā) rhythms; identical to the Fibonacci numbers.",
  N,
  count,                                   // count[n] = # rhythms of n morae = F(n+1)
  fibonacci: F.slice(1, N + 2).map(Number),// F(1..N+1)
  visibleSeq,                              // morae 1..10 → 1,2,3,5,8,13,21,34,55,89
  // the actual rhythms for small n, for the page's loom (capped to keep it small)
  rhythms: seqs.slice(0, 8).map((arr) => arr),
  pascalDiagonals: diagonals.slice(0, 11), // rising diagonals = Fibonacci
  hemacandraArray: hema,
  phi,
  checks: checks.length,
  passed: checks.filter((c) => c.pass).length,
};
writeFileSync(join(here, "artifact.json"), JSON.stringify(artifact, null, 2));

// ───────────────────────────────────────────────────────────────────────────
const passed = checks.filter((c) => c.pass).length;
console.log(`\nBefore the Rabbits — ${passed}/${checks.length} checks passed.`);
if (passed !== checks.length) {
  console.error("SOME CHECKS FAILED.");
  process.exit(1);
}
console.log("artifact.json written.");
