// research/dartboard-order/verify.mjs
// Locks every number the stratum "Twenty Between One and Five" shows, two ways:
// each computed value is re-derived from the reproducible engine AND checked
// against an independent anchor — a published OEIS b-file, a closed form, or an
// exhaustive brute-force search.
//
//   1. SCORING  — reproduce OEIS A242718 / A242681 / A242678 (ways to score n
//      with 1 / 2 / 3 darts) term-for-term from the 43-distinct-value model.
//   2. CHECKOUTS — reproduce OEIS A338551 (ways to finish n) from the
//      ordered-areas / finish-on-a-double model; derive the impossible finishes
//      and the maximum checkout; reproduce A241746 (first unscorable total).
//   3. ARRANGEMENT — the Cohen-Tonkes (2001) penalty D_p. Confirm the closed
//      forms by brute force on small n; compute the standard board and the
//      maximiser at n = 20; and record the one number that does NOT match the
//      paper — D_2 of the standard board — with the exact discrepancy.
//
// Run:  node research/dartboard-order/verify.mjs

import {
  VALUES, AREAS, FINISH_VALUES,
  scoreWays, firstUnscorable,
  checkoutWays, impossibleCheckouts, maxCheckout,
  STANDARD, penalty, isAlternating, L2_MAX_ARRANGEMENT,
  maxL1, maxL2, maxL3, maxL4, bruteMaxPenalty,
} from './engine.mjs';

let checks = 0, fails = 0;
const ok = (cond, msg) => { checks++; if (!cond) { fails++; console.log('  ✗ ' + msg); } };
const eqArr = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);

// ----------------------------------------------------------------------------
console.log('The board itself:');
ok(AREAS.length === 62, `62 scoring areas (got ${AREAS.length})`);
ok(VALUES.length === 43, `43 distinct single-dart values (got ${VALUES.length})`);
ok(FINISH_VALUES.length === 21, `21 finishing values: doubles + inner bull (got ${FINISH_VALUES.length})`);
ok(Math.max(...VALUES) === 60, `highest single-dart score is 60 = T20 (got ${Math.max(...VALUES)})`);

// ----------------------------------------------------------------------------
// 1. SCORING vs OEIS
// ----------------------------------------------------------------------------
console.log('\nScoring — reproducing OEIS A242718 / A242681 / A242678:');

// A242718: ways to score n with ONE dart, n = 1..24 (offset 1). 23 is the first
// number no single dart can make.
const A242718 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1];
ok(eqArr(A242718.map((_, i) => scoreWays(i + 1, 1)), A242718), 'A242718 (1 dart, n=1..24)');

// A242681: ways to score n with TWO darts, n = 2..25 (offset 2).
const A242681 = [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,11,11];
ok(eqArr(A242681.map((_, i) => scoreWays(i + 2, 2)), A242681), 'A242681 (2 darts, n=2..25)');

// A242678: ways to score n with THREE darts, n = 3..26 (offset 3).
const A242678 = [1,1,2,3,4,5,7,8,10,12,14,16,19,21,24,27,30,33,37,40,44,48,51,55];
ok(eqArr(A242678.map((_, i) => scoreWays(i + 3, 3)), A242678), 'A242678 (3 darts, n=3..26)');

// A241746: smallest total unscorable with k darts, k = 1..3.
const A241746 = [23, 103, 163];
ok(eqArr([1, 2, 3].map(firstUnscorable), A241746),
  `A241746 (first unscorable with 1/2/3 darts = ${A241746.join(', ')})`);

// ----------------------------------------------------------------------------
// 2. CHECKOUTS vs OEIS + the headline facts
// ----------------------------------------------------------------------------
console.log('\nCheckouts — reproducing OEIS A338551, and the finishes that cannot exist:');

// A338551: ways to check out n (ordered darts, finish on a double), n = 1..30.
const A338551 = [0,1,1,4,7,14,20,31,39,55,65,86,96,126,133,171,179,223,228,286,283,352,348,422,408,497,467,569,534,642];
ok(eqArr(A338551.map((_, i) => checkoutWays(i + 1)), A338551), 'A338551 (checkout ways, n=1..30)');

// The famous impossible finishes at or below the maximum, and the maximum itself.
const IMPOSSIBLE = [159, 162, 163, 165, 166, 168, 169];
ok(eqArr(impossibleCheckouts(170), IMPOSSIBLE),
  `impossible checkouts ≤170 are exactly ${IMPOSSIBLE.join(', ')}`);
ok(maxCheckout() === 170, `the maximum checkout is 170 (got ${maxCheckout()})`);
// 170 must be T20 + T20 + Bull(50): 60 + 60 + 50 — the only route, since a+b=120
// forces both setup darts to be the (unique) T20, and 50 is the only finish left.
ok(60 + 60 + 50 === 170 && checkoutWays(170) === 1,
  '170 = T20,T20,Bull — the unique highest checkout');
// A checkout must end on a double: an odd number below a double can still finish
// via a setup dart, but 1 can never be a legal finish.
ok(checkoutWays(1) === 0, '1 is not a legal checkout (no double is worth 1)');

// ----------------------------------------------------------------------------
// 3. THE ARRANGEMENT — Cohen & Tonkes (2001)
// ----------------------------------------------------------------------------
console.log('\nThe arrangement — penalty D_p, Cohen & Tonkes (2001):');

ok(eqArr([...STANDARD].sort((a, b) => a - b), Array.from({ length: 20 }, (_, i) => i + 1)),
  'the standard board is a permutation of 1..20');

// Confirm the closed forms by EXHAUSTIVE search on small n (fixing i_1=1 to
// quotient rotation). If brute force agrees with the formula, we trust the
// formula at n = 20 where 20! is out of reach.
for (const n of [4, 6, 8]) {
  ok(bruteMaxPenalty(n, 1).best === maxL1(n), `brute max L1(n=${n}) = ${maxL1(n)}`);
  ok(bruteMaxPenalty(n, 2).best === maxL2(n), `brute max L2(n=${n}) = ${maxL2(n)}`);
  ok(bruteMaxPenalty(n, 3).best === maxL3(n), `brute max L3(n=${n}) = ${maxL3(n)}`);
  ok(bruteMaxPenalty(n, 4).best === Math.round(maxL4(n)), `brute max L4(n=${n}) = ${Math.round(maxL4(n))}`);
}

// THE SECOND CORRECTION (claims pass, 2026-10-13). For odd n the paper says every
// alternating board has D_1 = 2k^2 (n = 2k+1), i.e. 2[n/2]^2. At n = 3 every
// arrangement scores |1-2| + |2-3| + |3-1| = 4, not 2. Exhaustive search for odd
// n gives (n^2 - 1)/2. The real board has n = 20, so nothing on it changes.
for (const n of [3, 5, 7, 9]) {
  const best = bruteMaxPenalty(n, 1).best;
  ok(best === (n * n - 1) / 2 && best !== 2 * Math.floor(n / 2) ** 2,
    `odd n=${n}: brute max L1 = ${best} = (n^2-1)/2, not the paper's 2[n/2]^2 = ${2 * Math.floor(n / 2) ** 2}`);
}

// L1 at n = 20.
const d1std = penalty(STANDARD, 1);
ok(d1std === 198, `D1(standard board) = 198 (got ${d1std})  — matches Cohen-Tonkes`);
ok(maxL1(20) === 200, 'max L1 = 200 = 2*(n/2)^2');
ok(!isAlternating(STANDARD), 'the standard board is NOT alternating (why it falls 2 short of 200)');
// Every alternating board scores exactly 200 (Theorem 2).
const someAlt = [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11];
ok(isAlternating(someAlt) && penalty(someAlt, 1) === 200,
  'an alternating board scores exactly 200 under L1');

// L2 at n = 20 — the maximiser, and the standard board.
ok(isAlternating(L2_MAX_ARRANGEMENT) && penalty(L2_MAX_ARRANGEMENT, 2) === maxL2(20),
  `the L2 maximiser scores ${maxL2(20)} (got ${penalty(L2_MAX_ARRANGEMENT, 2)})  — matches Selkirk's 2642`);
ok(maxL2(20) === 2642, "max L2 = 2642 (Selkirk's closed form n^3/3 - 4n/3 + 2)");

const d2std = penalty(STANDARD, 2);
ok(d2std === 2478, `D2(standard board) = 2478 (got ${d2std})`);

// THE CORRECTION. Cohen & Tonkes (2001), Further remark (2), print
// "D_2(A_d) = 2374" for the standard board. Recomputed from the very board they
// display (and from the canonical clockwise order confirmed by independent
// sources), the value is 2478. The paper's other n = 20 figures reproduce:
// D_1(A_d)=198, and the maxima 200 and 2642. So 2374 is a small arithmetic slip.
// (Its odd-n L1 maximum is a second slip; see below the small-n search.)
const PAPER_D2 = 2374;
ok(d2std !== PAPER_D2, `the paper's printed D2(A_d) = ${PAPER_D2} is NOT the true value`);
ok(d2std - PAPER_D2 === 104, `the discrepancy is exactly ${d2std - PAPER_D2} (2478 - 2374)`);
// Sanity that it is not a definitional artefact: the gap multiset that gives the
// (correct, agreed) D1=198 squares to 2478, full stop.
const gaps = STANDARD.map((v, i) => Math.abs(v - STANDARD[(i + 1) % 20]));
ok(gaps.reduce((a, b) => a + b, 0) === 198 && gaps.reduce((a, b) => a + b * b, 0) === 2478,
  'the standard gaps sum to 198 and their squares sum to 2478 (no dropped edge, no re-definition)');

// Higher powers, for completeness (the paper gives L3, L4 maxima; n even).
ok(maxL3(20) === 39260, `max L3 closed form at n=20 = ${maxL3(20)}`);
ok(maxL4(20) === 620978, `max L4 closed form at n=20 = ${maxL4(20)}`);

// ----------------------------------------------------------------------------
// The numbers the page prints, echoed for the reader who runs this.
// ----------------------------------------------------------------------------
console.log('\nComputed terms (what the stratum shows):');
console.log('  ways to score n with 3 darts, n=3..20 :', Array.from({ length: 18 }, (_, i) => scoreWays(i + 3, 3)).join(', '));
console.log('  ways to check out n, n=2..21          :', Array.from({ length: 20 }, (_, i) => checkoutWays(i + 2)).join(', '));
console.log('  impossible finishes ≤170             :', impossibleCheckouts(170).join(', '));
console.log('  maximum checkout                      :', maxCheckout(), '= T20, T20, Bull');
console.log('  L1: standard 198 / max 200            : short by', 200 - penalty(STANDARD, 1));
console.log('  L2: standard 2478 / max 2642          : short by', 2642 - penalty(STANDARD, 2),
  '  (paper misprinted the 2478 as 2374)');

console.log(`\n${checks - fails}/${checks} checks passed.`);
if (fails) { console.log(`${fails} FAILED.`); process.exit(1); }
