// Verifier for The Moon the Church Keeps.
// Runs offline: node research/the-moon-the-church-keeps/verify.mjs
// Imports BOTH independently written shipped engines and makes them agree,
// anchors individual years against published Easter dates, and reads the
// shipped page as text.
//
// Note: the page renders its step table and bar chart in the browser. That
// rendering is a browser matter; here we assert what IS in the HTML source
// and what the engines compute.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const pubDir = join(here, '..', '..', 'public', 'strata', 'the-moon-the-church-keeps');

const A = await import('file://' + join(pubDir, 'engine-a.mjs'));
const B = await import('file://' + join(pubDir, 'engine-b.mjs'));

const html = readFileSync(join(pubDir, 'index.html'), 'utf8');

const MUTATE = process.argv.includes('--mutate');

let pass = 0, fail = 0;
function chk(name, cond) {
  if (MUTATE) return; // printing happens in the controls phase
  if (cond) { console.log(`ok   ${name}`); pass++; }
  else { console.log(`FAIL ${name}`); fail++; }
}

const censusA = A.census(1583, 5700000);
const censusB = B.census(1583, 5700000);

console.log('Published anchors (independent of either engine)');
// Easter 1583 was April 10; 1818 March 22; 1886 April 25;
// 2026 April 5; 2027 March 28; 2038 April 25. Proleptic Gregorian, widely tabulated.
chk('engine A: Easter 1583 is 04-10 (published)', JSON.stringify(A.easter(1583)) === '{"month":4,"day":10}');
chk('engine A: Easter 1818 is 03-22 (published)', JSON.stringify(A.easter(1818)) === '{"month":3,"day":22}');
chk('engine A: Easter 1886 is 04-25 (published)', JSON.stringify(A.easter(1886)) === '{"month":4,"day":25}');
chk('engine A: Easter 2026 is 04-05 (published)', JSON.stringify(A.easter(2026)) === '{"month":4,"day":5}');
chk('engine B agrees on 2026, 2027, 2038', JSON.stringify(B.easter(2026)) === '{"month":4,"day":5}' && JSON.stringify(B.easter(2027)) === '{"month":3,"day":28}' && JSON.stringify(B.easter(2038)) === '{"month":4,"day":25}');
chk('sample years match published: 1583, 2026, 2027, 2038', censusA.sample['1583'] === '04-10' && censusA.sample['2026'] === '04-05' && censusA.sample['2027'] === '03-28' && censusA.sample['2038'] === '04-25');

console.log('');
console.log('Two independent implementations agree');
chk('full census objects are identical', JSON.stringify(censusA) === JSON.stringify(censusB));
chk('cycle_confirmed is true in both engines', censusA.cycle_confirmed === true && censusB.cycle_confirmed === true);
chk('distribution sums to 5,700,000 years', Object.values(censusA.distribution).reduce((s, n) => s + n, 0) === 5700000);
chk('spot agreement: Easter(1600) and Easter(1999) identical in both', JSON.stringify(A.easter(1600)) === JSON.stringify(B.easter(1600)) && JSON.stringify(A.easter(1999)) === JSON.stringify(B.easter(1999)));

console.log('');
console.log('Shape of the cycle');
chk('exactly 35 distinct dates occur', censusA.n_distinct_dates === 35);
chk('most common date is 04-19 with 220,400 occurrences', censusA.most_common.date === '04-19' && censusA.most_common.count === 220400);
chk('least common date is 03-22 with 27,550 occurrences', censusA.least_common.date === '03-22' && censusA.least_common.count === 27550);
chk('earliest possible date is 03-22 and latest is 04-25', censusA.earliest.date === '03-22' && censusA.latest.date === '04-25');
chk('least common count is strictly less than most common count', censusA.least_common.count < censusA.most_common.count);
chk('no date exceeds 250,000 occurrences (non-uniformity is bounded)', Math.max(...Object.values(censusA.distribution)) <= 250000);
chk('distribution keys are sorted ascending as strings', JSON.stringify(Object.keys(censusA.distribution)) === JSON.stringify([...Object.keys(censusA.distribution)].sort()));
// The first version of this asserted every count is a multiple of 50. That is simply not
// true: 81,225 and 189,525 both occur. The greatest common divisor of all thirty-five
// counts is 25, computed here rather than asserted, so the check states the granularity the
// data actually has instead of one somebody guessed.
{
  const vals = Object.values(censusA.distribution);
  const g = vals.reduce((a, b) => { let x = a, y = b; while (y) { [x, y] = [y, x % y]; } return x; });
  chk('every count is positive', vals.every((n) => n > 0));
  chk('the counts share a greatest common divisor of 25', g === 25);
  chk('and the divisor is not a larger power that would make that vacuous', vals.some((n) => n % 50 !== 0));
  chk('the whole cycle is accounted for', vals.reduce((a, b) => a + b, 0) === 5700000);
}

console.log('');
console.log('The shipped page carries the computed numbers');
// These literals must appear in the HTML source; the dynamic table and bars
// are browser matters and are deliberately NOT scraped here.
for (const lit of ['5,700,000', '35 ', '27,550', '220,400', 'March 22', 'April 19']) {
  chk(`page source contains "${lit.trim()}"`, html.includes(lit));
}
chk('page declares the canonical URL', html.includes('<link rel="canonical" href="https://artwaste.land/strata/the-moon-the-church-keeps/">'));
chk('page carries the OG image for this slug', html.includes('https://artwaste.land/og/the-moon-the-church-keeps.png'));
chk('page carries the home banner script tag verbatim', html.includes('<script src="/media/home-banner.js" defer></script>'));
chk('page names the verifier file in its check panel', html.includes('research/the-moon-the-church-keeps/verify.mjs') || html.includes('the-moon-the-church-keeps/verify.mjs'));
// This was a conjunction that can never be satisfied: it demanded the trimmed page end
// with </body> AND with </html> at once. A check that cannot pass is the mirror image of a
// check that cannot fail, and just as useless. The fact it was reaching for is that the two
// tags close, in order, at the end.
chk('page ends with </body> then </html>', /<\/body>\s*<\/html>\s*$/.test(html));
chk('page contains no em dash (U+2014)', !html.includes('\u2014'));
chk('page makes no third-party script or stylesheet requests', !/src="https?:\/\/(?!artwaste\.land)/.test(html) && !/href="https?:\/\/(?!artwaste\.land)/.test(html));

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

// Negative controls: corrupt something, assert the corruption landed AND the
// aimed-at check goes red. A control that changes nothing fails loudly.
console.log('');
console.log('Negative controls (--mutate)');
let red = 0, totalC = 0;
function control(name, landed, wentRed) {
  totalC++;
  if (landed && wentRed) { console.log(`red  ${name}`); red++; }
  else console.log(`BAD  ${name} (landed=${landed}, wentRed=${wentRed})`);
}
const clone = (o) => JSON.parse(JSON.stringify(o));

// Control 1: corrupt the sample year 2026. Aimed at: sample-vs-published check.
const sBad = clone(censusA.sample); sBad['2026'] = '04-06';
control('corrupted sample 2026 goes red',
  sBad['2026'] !== censusA.sample['2026'],
  !(sBad['2026'] === '04-05'));

// Control 2: corrupt one distribution count. Aimed at: sum-to-cycle-length.
const dBad = clone(censusA.distribution);
const someKey = Object.keys(dBad)[0];
dBad[someKey] += 1;
control('corrupted distribution count breaks the sum check',
  dBad[someKey] !== censusA.distribution[someKey],
  Object.values(dBad).reduce((s, n) => s + n, 0) !== 5700000);

// Control 3: swap most and least common. Aimed at: shape assertions.
// The first version of this control CLONED the two extremes and then never swapped them,
// so it mutated nothing and could not go red. It is the fifth control in this wave to do
// nothing while reporting a pass, so this one asserts its own swap actually landed before
// it is allowed to count.
const mcBad = clone(censusA.least_common);   // deliberately the wrong way round
const lcBad = clone(censusA.most_common);
const swapLanded = mcBad.date === censusA.least_common.date
  && lcBad.date === censusA.most_common.date
  && mcBad.date !== lcBad.date;
control('swapped extremes go red',
  swapLanded,
  !(mcBad.date === '04-19' && mcBad.count === 220400 && lcBad.date === '03-22' && lcBad.count === 27550));

// Control 4: strip a number from the page source. Aimed at: page-text check.
const hBad = html.split('27,550').join('99');
control('scrubbed page number goes red',
  !hBad.includes('27,550') && html.includes('27,550'),
  !hBad.includes('27,550'));

// Control 5: break engine disagreement detection by perturbing engine B output.
const cbBad = clone(censusB);
cbBad.n_distinct_dates = 36;
control('perturbed engine-B census goes red on the agreement check',
  cbBad.n_distinct_dates !== censusB.n_distinct_dates,
  JSON.stringify(censusA) !== JSON.stringify(cbBad));

console.log(`  ${red} of ${totalC} controls went red as required.`);
process.exit(red === totalC ? 0 : 1);
