// verify.mjs — the honest core of the "Plain Changes, rung" instrument.
//
// The instrument rings four kinds of true thing: Rounds, Plain Hunt, Plain Bob
// (the method bands actually ring), and the full Plain Changes / SJT extent.
// The never-lie rule applies to sound the same way it applies to a stratum's
// numbers: a sequence the page calls "Plain Bob Minor" must BE Plain Bob Minor,
// and "an extent" must visit every row exactly once. This file generates each
// method from first principles, by exactly the same code the page ships, and
// proves the claims the page makes about it — so the audio rests on a checked
// foundation, not an assertion.
//
//   node verify.mjs            run all checks, print a table, exit non-zero on any fail
//
// The two engines (SJT extent, Plain Bob via place notation) are duplicated
// verbatim in public/instruments/plain-changes/index.html; keep them in step.

const FACT = [1, 1, 2, 6, 24, 120, 720, 5040, 40320];

/* ── generators ─────────────────────────────────────────────────────────── */

// Plain changes = Steinhaus–Johnson–Trotter (largest-mobile-element): all n!
// permutations, each one adjacent swap from the last, closing back to rounds.
function plainChanges(n) {
  const perm = Array.from({ length: n }, (_, i) => i + 1);
  const dir = Array(n + 1).fill(-1);
  const pos = Array(n + 1).fill(0);
  for (let i = 0; i < n; i++) pos[perm[i]] = i;
  const rows = [perm.slice()];
  while (true) {
    let mob = 0, mi = -1;
    for (let v = 1; v <= n; v++) {
      const i = pos[v], j = i + dir[v];
      if (j >= 0 && j < n && perm[j] < v && v > mob) { mob = v; mi = i; }
    }
    if (mob === 0) break;
    const i = mi, j = i + dir[mob];
    [perm[i], perm[j]] = [perm[j], perm[i]];
    pos[perm[i]] = i; pos[perm[j]] = j;
    for (let v = mob + 1; v <= n; v++) dir[v] = -dir[v];
    rows.push(perm.slice());
  }
  return rows;
}

// Plain hunt: alternating disjoint adjacent swaps; 2n rows back to rounds.
function plainHunt(n) {
  let perm = Array.from({ length: n }, (_, i) => i + 1);
  const rows = [perm.slice()];
  for (let step = 0; step < 2 * n; step++) {
    const next = perm.slice();
    const start = (step % 2 === 0) ? 0 : 1;
    for (let i = start; i + 1 < n; i += 2) [next[i], next[i + 1]] = [next[i + 1], next[i]];
    perm = next; rows.push(perm.slice());
  }
  return rows;
}

// Place notation: a "change" is a set of positions (1-indexed) that STAY (make a
// place); every other position must pair with its neighbour as an adjacent swap.
// applyPN throws if the notation is not a product of disjoint adjacent
// transpositions over the non-place positions — so an ill-formed change can
// never silently produce a wrong row.
function applyPN(perm, places) {
  const n = perm.length;
  const out = perm.slice();
  const stay = new Set(places);
  let i = 0;
  while (i < n) {
    if (stay.has(i + 1)) { i++; continue; }
    if (i + 1 >= n || stay.has(i + 2)) throw new Error(`bad place notation {${places}} at pos ${i + 1} on ${n}`);
    [out[i], out[i + 1]] = [out[i + 1], out[i]];
    i += 2;
  }
  return out;
}

// One lead of Plain Bob place notation on n bells. The internal 2n-1 changes are
// exactly plain hunt; only the lead-end change differs — "seconds made":
//   even n: lead end = {1,2}   (Minimus, Minor, Major, …)
//   odd  n: lead end = {1,2,n} (Doubles, Triples, …) — the back place is forced
//                               because an odd remainder can't pair otherwise.
function plainBobLeadNotation(n) {
  const even = n % 2 === 0;
  const huntA = even ? [] : [n];   // change 1 (and every odd change)
  const huntB = even ? [1, n] : [1]; // change 2 (and every even change)
  const lead = [];
  for (let c = 1; c <= 2 * n; c++) lead.push(c % 2 === 1 ? huntA : huntB);
  lead[2 * n - 1] = even ? [1, 2] : [1, 2, n]; // replace the final hunt change
  return lead;
}

// The Plain Bob "plain course": ring leads until the bells come home to rounds.
// Returns the rows of one full plain course (ending back at rounds).
function plainBobCourse(n) {
  const lead = plainBobLeadNotation(n);
  let perm = Array.from({ length: n }, (_, i) => i + 1);
  const rows = [perm.slice()];
  const rounds = perm.join('');
  for (let safety = 0; safety < n * 4; safety++) {
    for (const change of lead) { perm = applyPN(perm, change); rows.push(perm.slice()); }
    if (perm.join('') === rounds) break;
  }
  return rows;
}

// Independent enumerator (lexicographic) — never used to generate what's rung,
// only to confirm the SJT extent really is the whole symmetric group.
function allPermsLex(n) {
  const out = []; const a = Array.from({ length: n }, (_, i) => i + 1);
  (function go(k) {
    if (k === n) { out.push(a.slice()); return; }
    for (let i = k; i < n; i++) { [a[k], a[i]] = [a[i], a[k]]; go(k + 1); [a[k], a[i]] = [a[i], a[k]]; }
  })(0);
  return out;
}

/* ── the legality / truth predicates the page also runs live ──────────────── */

// A change is legal iff every bell moves at most one place AND the transition is
// a product of disjoint adjacent transpositions.
function legalChange(a, b, n) {
  for (let i = 0; i < n; i++) if (Math.abs(b.indexOf(a[i]) - i) > 1) return false;
  let i = 0;
  while (i < n) {
    if (a[i] === b[i]) i++;
    else if (i + 1 < n && a[i] === b[i + 1] && a[i + 1] === b[i]) i += 2;
    else return false;
  }
  return true;
}

// Every consecutive change in `rows` is legal.
function allChangesLegal(rows, n) {
  for (let r = 1; r < rows.length; r++) if (!legalChange(rows[r - 1], rows[r], n)) return false;
  return true;
}

// `rows` is a closed round block: starts and ends at rounds, and the rows
// strictly between are distinct from each other and from rounds (so each row in
// the block is rung exactly once before coming home).
function isTrueClosedBlock(rows, n) {
  const rounds = Array.from({ length: n }, (_, i) => i + 1).join('');
  if (rows[0].join('') !== rounds) return { ok: false, why: 'does not start at rounds' };
  if (rows[rows.length - 1].join('') !== rounds) return { ok: false, why: 'does not return to rounds' };
  const body = rows.slice(0, -1); // drop the repeat of rounds at the very end
  const seen = new Set();
  for (const r of body) {
    const k = r.join('');
    if (seen.has(k)) return { ok: false, why: `row ${k} rung twice` };
    seen.add(k);
  }
  return { ok: true, distinct: seen.size };
}

/* ── run the checks ───────────────────────────────────────────────────────── */

let pass = 0, fail = 0;
const log = [];
function check(name, cond, detail = '') {
  (cond ? pass++ : fail++);
  log.push(`  ${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  — ' + detail : ''}`);
}

console.log('PLAIN CHANGES, RUNG — verification of every method the instrument plays\n');

// 1 — Plain Hunt: 2n rows, returns to rounds, every change legal, visits 2n orders.
console.log('Plain Hunt');
for (const n of [3, 4, 5, 6, 8]) {
  const rows = plainHunt(n);
  const t = isTrueClosedBlock(rows, n);
  check(`hunt n=${n}: length 2n=${2 * n}`, rows.length - 1 === 2 * n, `got ${rows.length - 1}`);
  check(`hunt n=${n}: legal throughout`, allChangesLegal(rows, n));
  check(`hunt n=${n}: closed & no repeat before return`, t.ok, t.why || `${t.distinct} distinct`);
  check(`hunt n=${n}: visits exactly 2n=${2 * n} orders`, t.ok && t.distinct === 2 * n);
  // On three bells 2n = 6 = 3!, so plain hunt already IS a full extent; for every
  // larger n it covers only 2n of the n! orders, which is why the craft needed more.
  if (n === 3) check(`hunt n=3: 2n = 3! — plain hunt already covers the whole extent`, 2 * n === FACT[n]);
  else check(`hunt n=${n}: 2n < n! — plain hunt does NOT cover the extent`, 2 * n < FACT[n]);
}

// 2 — Plain Bob: the real method. Plain course is (n-1) leads of 2n changes,
//     true (every row once before return), legal, and treble plain-hunts.
console.log('\nPlain Bob (plain course)');
for (const n of [4, 5, 6, 8]) {
  const rows = plainBobCourse(n);
  const t = isTrueClosedBlock(rows, n);
  const leads = (rows.length - 1) / (2 * n);
  check(`bob n=${n}: plain course = (n-1) leads = ${n - 1}`, leads === n - 1, `got ${leads}`);
  check(`bob n=${n}: length (n-1)*2n = ${(n - 1) * 2 * n}`, rows.length - 1 === (n - 1) * 2 * n, `got ${rows.length - 1}`);
  check(`bob n=${n}: legal throughout`, allChangesLegal(rows, n));
  check(`bob n=${n}: TRUE (every row of the course rung once before return)`, t.ok, t.why || `${t.distinct} distinct`);
  // The treble's path within a lead must be exactly plain hunt (1 → up to n → back to 1).
  const trebleLead = rows.slice(0, 2 * n + 1).map(r => r.indexOf(1) + 1);
  const huntPath = plainHunt(n).map(r => r.indexOf(1) + 1);
  check(`bob n=${n}: treble plain-hunts every lead`, trebleLead.join() === huntPath.join(),
    `treble: ${trebleLead.join(' ')}`);
}

// 3 — Plain Bob Minimus is *exactly* the full extent on 4 (a famous fact:
//     no calls are needed on four bells — the plain course is all 24 rows).
console.log('\nPlain Bob Minimus = the whole extent on 4');
{
  const course = plainBobCourse(4);
  const t = isTrueClosedBlock(course, 4);
  check('bob minimus: plain course has 24 rows', course.length - 1 === 24, `got ${course.length - 1}`);
  check('bob minimus: all 24 orders, each once', t.ok && t.distinct === 24, `${t.distinct} distinct`);
}

// 4 — Plain Changes / SJT extent: all n! orders exactly once, every change a
//     single adjacent swap, closes back to rounds by one legal change.
console.log('\nPlain Changes (SJT full extent)');
for (const n of [3, 4, 5, 6]) {
  const rows = plainChanges(n);
  const seen = new Set(rows.map(r => r.join('')));
  const lexSet = new Set(allPermsLex(n).map(r => r.join('')));
  const coversAll = seen.size === FACT[n] && [...lexSet].every(k => seen.has(k));
  check(`sjt n=${n}: exactly n!=${FACT[n]} rows`, rows.length === FACT[n], `got ${rows.length}`);
  check(`sjt n=${n}: every order exactly once (vs independent lex enumeration)`, coversAll, `${seen.size} distinct`);
  check(`sjt n=${n}: every change a single adjacent swap`, allChangesLegal(rows, n));
  check(`sjt n=${n}: closes to rounds by one legal change`,
    legalChange(rows[rows.length - 1], rows[0], n));
}

console.log('\n' + log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
