// verify-the-seventh-stanza.mjs: the offline check behind /strata/the-seventh-stanza/.
//
//   node research/sestina-studio/verify-the-seventh-stanza.mjs
//
// What it is for. Every number the page prints is either computed by spiral.mjs in the
// reader's browser or read out of corpus.json, and both come from this directory. That
// removes drift but it does not establish that any of it is RIGHT, so this file exists to
// check the engine against things it did not produce:
//
//   • the sestina table as the reference works print it, typed in by hand here;
//   • the terms of OEIS A054639, as published;
//   • Asveld's independent three-case characterisation of which n work;
//   • Bringer's 1969 corollary, tested rather than quoted;
//   • Roubaud's published 141, which is wrong, so the check has to report it wrong;
//   • the nine poems, re-measured from the raw source files and re-hashed.
//
// It can fail. Several of these assertions went red while the page was being built.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import * as S from './spiral.mjs';
import { POEMS, EXCLUDED } from './poems.mjs';
import {
  readSource, extract, stanzas, measure, textFromWikisourceHtml, latinSquare, endWord,
} from './corpus.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'the-seventh-stanza');

let pass = 0, fail = 0;
const ok = (cond, label, detail = '') => {
  if (cond) { pass++; console.log(`  ok   ${label}`); }
  else { fail++; console.log(`  FAIL ${label}${detail ? '  · ' + detail : ''}`); }
};
const eq = (a, b, label) => ok(JSON.stringify(a) === JSON.stringify(b), label,
  `got ${JSON.stringify(a)} want ${JSON.stringify(b)}`);

const section = (t) => console.log(`\n${t}`);

// ---------------------------------------------------------------------------
section('1 · the sestina table, against the order the reference works print');
// ---------------------------------------------------------------------------
// Typed in by hand from the standard presentation of the form, NOT generated, so
// that an error in spiralOrder cannot hide by also generating the expectation.
const CANONICAL = [
  [1, 2, 3, 4, 5, 6],
  [6, 1, 5, 2, 4, 3],
  [3, 6, 4, 1, 2, 5],
  [5, 3, 2, 6, 1, 4],
  [4, 5, 1, 3, 6, 2],
  [2, 4, 6, 5, 3, 1],
];
const table = S.rows(6, 7);
CANONICAL.forEach((row, i) => eq(table[i], row, `stanza ${i + 1} is ${row.join('')}`));
eq(table[6], CANONICAL[0], 'stanza 7 is identical to stanza 1');
eq(S.spiralOrder(6), [6, 1, 5, 2, 4, 3], 'the reading order is 6 1 5 2 4 3');
ok(S.orderOf(6) === 6, 'the permutation has order 6');
ok(S.cycles(6).length === 1 && S.cycles(6)[0].length === 6, 'it is a single six-cycle');

// The Latin-square property the form exists for.
{
  const grid = table.slice(0, 6);
  let good = true;
  for (let c = 0; c < 6; c++) if (new Set(grid.map((r) => r[c])).size !== 6) good = false;
  for (const r of grid) if (new Set(r).size !== 6) good = false;
  ok(good, 'the six stanzas form a Latin square: every word in every position once');
}

// A negative control. If spiralOrder were the identity, or a rotation, the tests
// above must not pass. Check that the rotation really is a different permutation,
// so "matches the canonical table" is a discriminating claim.
{
  const rot = [6, 1, 2, 3, 4, 5];
  ok(JSON.stringify(S.spiralOrder(6)) !== JSON.stringify(rot),
    'control: the spiral is not the rotation Spenser used');
}

// ---------------------------------------------------------------------------
section('2 · the arithmetic, against the permutation');
// ---------------------------------------------------------------------------
{
  let bad = 0;
  for (let n = 1; n <= 2000; n++) {
    const tau = S.permutation(n);
    for (let k = 1; k <= n; k++) if (tau[k] !== S.doubleFold(n, k)) bad++;
  }
  ok(bad === 0, 'tau(k) = 2k or 2n+1-2k for every k, every n up to 2000', `${bad} disagreements`);
}
{
  // and that the folded form really is +/- 2k mod 2n+1
  let bad = 0;
  for (let n = 1; n <= 500; n++) {
    const M = 2 * n + 1;
    for (let k = 1; k <= n; k++) {
      const t = S.doubleFold(n, k);
      if ((2 * k - t) % M !== 0 && (2 * k + t) % M !== 0) bad++;
    }
  }
  ok(bad === 0, 'every step is +/-2k modulo 2n+1', `${bad} disagreements`);
}

// ---------------------------------------------------------------------------
section('3 · the Queneau numbers, against the published terms of OEIS A054639');
// ---------------------------------------------------------------------------
// Transcribed from the b-file terms shown on the sequence page. Independent of us.
const A054639 = [1, 2, 3, 5, 6, 9, 11, 14, 18, 23, 26, 29, 30, 33, 35, 39, 41, 50, 51, 53,
  65, 69, 74, 81, 83, 86, 89, 90, 95, 98, 99, 105, 113, 119, 131, 134, 135, 146, 155, 158,
  173, 174, 179, 183, 186, 189, 191, 194, 209, 210, 221, 230, 231, 233, 239];
{
  const mine = S.queneauNumbers(239);
  eq(mine, A054639, 'our Queneau numbers up to 239 are exactly the published terms');
  ok(S.isQueneau(6), '6 is a Queneau number');
  for (const n of [4, 7, 8, 10, 12, 13]) ok(!S.isQueneau(n), `${n} is not a Queneau number`);
}
// the specific failures the page describes
eq(S.cycles(4).map((c) => c.length).sort(), [1, 3], 'four end-words: cycles of 3 and 1');
ok(S.cycles(4).some((c) => c.length === 1 && c[0] === 3), 'with four, position 3 never moves');
eq(S.cycles(8).map((c) => c.length), [4, 4], 'eight end-words: two four-cycles');
eq(S.cycles(12).map((c) => c.length).sort((a, b) => a - b), [2, 10],
  'twelve end-words: a ten and a two, so a twelve-word sestina cannot spiral');

// ---------------------------------------------------------------------------
section('4 · Asveld\'s characterisation, against the computed cycle structure');
// ---------------------------------------------------------------------------
{
  let bad = 0, byCase = { 1: 0, 2: 0, 3: 0 };
  for (let n = 2; n <= 3000; n++) {
    const a = S.asveldCase(n);
    const q = S.isQueneau(n);
    if ((a.case !== 0) !== q) bad++;
    if (q && a.case) byCase[a.case]++;
  }
  ok(bad === 0, 'Asveld\'s three cases agree with the cycle structure for every n from 2 to 3000',
    `${bad} disagreements`);
  ok(byCase[1] > 0 && byCase[2] > 0 && byCase[3] > 0,
    `all three of Asveld's cases actually occur (${byCase[1]}/${byCase[2]}/${byCase[3]})`);
}

// ---------------------------------------------------------------------------
section('5 · Roubaud\'s 141, which the page says is wrong');
// ---------------------------------------------------------------------------
{
  const c = S.cycles(141);
  ok(!S.isQueneau(141), '141 does not work, contrary to the published claim');
  eq(c.map((x) => x.length), [47, 47, 47], '141 breaks into three cycles of 47');
  ok(S.orderOf(141) === 47, 'its order is 47, which is 141/3');
}

// ---------------------------------------------------------------------------
section('6 · Bringer 1969: order equals the length of the orbit of 1');
// ---------------------------------------------------------------------------
{
  let bad = 0;
  for (let n = 1; n <= 4000; n++) if (S.orderOf(n) !== S.orbitOfOne(n)) bad++;
  ok(bad === 0, 'order = |orbit of 1| for every n up to 4000 (Bringer, Lemme 1 + Corollaire)',
    `${bad} counterexamples`);
  // and the reason, tested directly: applying the map p times is the identity
  let bad2 = 0;
  for (let n = 2; n <= 800; n++) {
    const p = S.orbitOfOne(n);
    const tau = S.permutation(n);
    for (let k = 1; k <= n; k++) {
      let x = k;
      for (let i = 0; i < p; i++) x = tau[x];
      if (x !== k) bad2++;
    }
  }
  ok(bad2 === 0, 'and the reason holds: p applications return every position to itself',
    `${bad2} failures`);
  // negative control: a permutation whose order is not its orbit-of-1 length exists,
  // so the property above is not vacuous.
  ok(true === ((() => {
    const tau = [0, 2, 3, 1, 5, 4]; // (1 2 3)(4 5)
    let len = 0, x = 1;
    do { x = tau[x]; len++; } while (x !== 1);
    return len === 3; // order is 6, orbit of 1 is 3
  })()), 'control: (123)(45) has order 6 but orbit-of-1 length 3, so the claim has content');
}
{
  const scan = JSON.parse(fs.readFileSync(path.join(HERE, 'orbit-scan.json'), 'utf8'));
  ok(scan.held === true && scan.counterexamples.length === 0,
    `the committed wide scan found no counterexample up to n = ${scan.scannedTo}`);
  ok(scan.scannedTo > scan.publishedBound,
    `and it goes past the published bound of ${scan.publishedBound}`);
}

// ---------------------------------------------------------------------------
section('7 · the poems, re-measured from the raw sources');
// ---------------------------------------------------------------------------
const corpus = JSON.parse(fs.readFileSync(path.join(HERE, 'corpus.json'), 'utf8'));
const manifest = fs.readFileSync(path.join(HERE, 'sources', 'MANIFEST.md'), 'utf8');

ok(corpus.poems.length === POEMS.length, `all ${POEMS.length} poems are in the committed corpus`);

for (const p of POEMS) {
  const raw = readSource(p.file);
  const sha = crypto.createHash('sha256').update(raw).digest('hex');
  const rec = corpus.poems.find((x) => x.id === p.id);
  ok(rec && rec.sha256 === sha, `${p.id}: source file hash matches the committed measurement`);
  ok(manifest.includes(p.file), `${p.id}: source file is listed in MANIFEST.md`);

  const plain = p.html ? textFromWikisourceHtml(raw, { from: p.from, to: p.to }) : raw;
  const cut = p.html
    ? { from: plain.split('\n')[0], to: plain.split('\n').filter(Boolean).slice(-1)[0] }
    : { from: p.from, to: p.to };
  const cutText = extract(plain, { ...cut, strip: p.strip, repairs: p.repairs });
  const m = measure(stanzas(cutText.text), p.n, p.equivalents || {});

  ok(!m.error, `${p.id}: stanza 1 yields exactly ${p.n} distinct end-words`);
  ok(m.stanzas === rec.bodyStanzas, `${p.id}: ${m.stanzas} full stanzas, as committed`);
  ok(m.lenient.spiralCount === rec.lenientSpiral && m.lenient.judgedCount === rec.lenientJudged,
    `${p.id}: ${m.lenient.spiralCount} of ${m.lenient.judgedCount} transitions are the spiral, as committed`);
  ok(m.unresolvedEndWords === 0,
    `${p.id}: every line-end resolves to one of the poem's own words`);

  const L = latinSquare(m.lenientRows, p.n);
  ok(JSON.stringify(L.isLatin ?? null) === JSON.stringify(rec.latin.isLatin ?? null),
    `${p.id}: Latin-square verdict (${L.isLatin}) matches the committed one`);

  // Stripping editorial apparatus must never eat a word of the poem. Petrarch's
  // source hangs line numbers on the ends of lines and Sidney's interleaves page
  // numbers and speaker names between them, so the strip patterns DO change what
  // the last token of a line is; what they must not do is remove a rhyme-word.
  {
    const bare = extract(plain, { ...cut, strip: [], repairs: p.repairs });
    let removed = bare.text;
    for (const re of p.strip) removed = removed.replace(re, ' ');
    const gone = bare.text.length - removed.replace(/ /g, '').length;
    const removedText = [];
    for (const re of p.strip) {
      const rx = new RegExp(re.source, re.flags);
      let mm;
      while ((mm = rx.exec(bare.text))) { removedText.push(mm[0]); if (!rx.global) break; }
    }
    const words = new Set((m.words || []).map((w) => w.toLocaleLowerCase()));
    const eaten = removedText.join(' ').toLocaleLowerCase().match(/\p{L}+/gu) || [];
    ok(!eaten.some((w) => words.has(w)),
      `${p.id}: stripping apparatus removed no end-word of the poem` +
      (p.strip.length ? ` (${removedText.length} spans, ${gone} chars)` : ' (nothing stripped)'));
  }
  // And the structure the extraction claims: every body stanza is exactly n lines.
  {
    const sts = stanzas(cutText.text);
    const body = sts.filter((s) => s.length === p.n);
    // Sidney's envoi is split between his two shepherds, so it arrives as two
    // blocks rather than one. Count leftover LINES, which an envoi bounds at n.
    const leftover = sts.filter((s) => s.length !== p.n).reduce((a, s) => a + s.length, 0);
    ok(body.length === rec.bodyStanzas && leftover <= p.n,
      `${p.id}: ${body.length} stanzas of exactly ${p.n} lines, plus a ${leftover}-line envoi`);
  }
}

// the six that follow the spiral throughout, named rather than counted
{
  const all = corpus.poems.filter((p) => p.lenientAllSpiral).map((p) => p.id).sort();
  eq(all, ['arnaut', 'dante', 'kipling', 'petrarch22', 'petrarch332', 'sidney'],
    'exactly these six poems use the spiral at every transition');
}
// the three that do not, and how
{
  const sp = corpus.poems.find((p) => p.id === 'spenser');
  eq(sp.observed, [6, 1, 2, 3, 4, 5], 'Spenser uses the rotation');
  ok(sp.observedConsistent, 'and uses the same one at every transition');
  ok(sp.observedShape.singleCycle, 'the rotation is also a single six-cycle, so his form closes');
  ok(sp.latin.isLatin, 'and his grid is still a Latin square');

  const sw = corpus.poems.find((p) => p.id === 'swinburne-sestina');
  ok(sw.lenientSpiral === 0, 'Swinburne\'s Sestina never uses the spiral');
  ok(!sw.observedConsistent, 'and does not even use one fixed permutation');
  ok(sw.alternation.all === true, 'its rhyme classes alternate in every stanza');
  ok(sw.spiralAlternates.stanza1 === true && sw.spiralAlternates.stanza2 === false,
    'while the spiral would break that alternation at stanza 2');
  ok(sw.latin.isLatin === false && sw.latin.pairsUsed === 32,
    'and it reaches only 32 of 36 word-and-position pairs');

  const li = corpus.poems.find((p) => p.id === 'swinburne-lisa');
  ok(li.n === 12 && !S.isQueneau(12), 'The Complaint of Lisa has 12 end-words, which cannot spiral');
  ok(li.lenientSpiral === 0 && li.lenientJudged === 11, 'none of its 11 transitions is the spiral');
  ok(li.latin.isLatin === false && li.latin.pairsUsed === 100,
    'it reaches 100 of 144 word-and-position pairs');
  // every transition begins with the spiral's first two moves
  const heads = corpus.poems.find((p) => p.id === 'swinburne-lisa');
  ok(heads.observed[0] === 12 && heads.observed[1] === 1,
    'and each begins by taking the last word to the front and the first to second place');
}
// the double sestinas repeat at stanza 7
for (const id of ['sidney', 'petrarch332']) {
  const p = corpus.poems.find((x) => x.id === id);
  const rows = p.lenientRows ? p.lenientRows.filter((r) => r.length === 6) : null;
  ok(rows && rows.length >= 7 && rows[0].join('') === rows[6].join(''),
    `${id}: stanza 7 reproduces stanza 1 exactly`);
}
// exactly one repair, and it is Arnaut's
{
  const applied = corpus.poems.flatMap((p) => p.repairs.filter((r) => r.applied));
  ok(applied.length === 1 && applied[0].from === 'd’ncle',
    `exactly one character-level repair in the whole corpus (${applied.length})`);
}
// and the poem left out on purpose is still left out
{
  ok(EXCLUDED.length === 1 && /Pound/.test(EXCLUDED[0].author), 'Pound is recorded as excluded');
  const files = fs.readdirSync(path.join(HERE, 'sources'));
  ok(!files.some((f) => /pound/i.test(f)), 'and no Pound text is committed in sources/');
}

// ---------------------------------------------------------------------------
section('8 · the page loads the same engine, and prints nothing it did not compute');
// ---------------------------------------------------------------------------
{
  const a = fs.readFileSync(path.join(HERE, 'spiral.mjs'));
  const b = fs.readFileSync(path.join(PAGE, 'spiral.mjs'));
  ok(a.equals(b), 'public copy of spiral.mjs is byte-identical to the research one');

  const html = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');
  ok(html.includes("import * as S from '/strata/the-seventh-stanza/spiral.mjs'"),
    'the page imports that module rather than reimplementing it');
  ok(!/\bfunction\s+spiralOrder\b/.test(html), 'and does not define its own copy of the rule');

  const served = JSON.parse(fs.readFileSync(path.join(PAGE, 'corpus.json'), 'utf8'));
  eq(served.totals, corpus.totals, 'the served corpus totals match the research ones');
  const servedScan = JSON.parse(fs.readFileSync(path.join(PAGE, 'orbit-scan.json'), 'utf8'));
  eq(servedScan, JSON.parse(fs.readFileSync(path.join(HERE, 'orbit-scan.json'), 'utf8')),
    'the served scan result matches the research one');

  // The numbers the prose states in words must match the data.
  ok(html.includes('nine poems, three languages'), 'the byline states the corpus size');
  ok(corpus.totals.poems === 9 && corpus.totals.languages === 3, 'and that is the corpus size');
  ok(corpus.totals.unresolved === 0, 'no line-end anywhere is unresolved, as the page claims');
  ok(corpus.totals.variantEndWords === 16, `16 variant line-ends, as the page states (${corpus.totals.variantEndWords})`);
  ok(corpus.totals.latinSquares === 7, `7 of 9 poems reach the Latin square (${corpus.totals.latinSquares})`);
}

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