#!/usr/bin/env node
'use strict';

import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const PUBLICATION_YEAR = 2026;
const BROAD_DECADE_START = 1660;
const LITERAL_YEAR = 1600;
const TAX_YEAR = 1655;
const DEFAULT_UNIT = 480;
const UNIT_OPTIONS = [120, 480, 1000];
const ROMAN_RATE = 1 / 10;

const split = n => ({ fallen: n * ROMAN_RATE, survivors: n * (1 - ROMAN_RATE) });
const pct = (part, whole) => 100 * part / whole;
const age = (now, then) => now - then;
let passed = 0;
let failed = 0;
function check(name, condition, detail = '') {
  if (condition) { passed++; console.log(`PASS ${name}${detail ? `: ${detail}` : ''}`); }
  else { failed++; console.log(`FAIL ${name}${detail ? `: ${detail}` : ''}`); }
}

console.log('does-decimate-mean-one-in-ten :: offline verifier');

for (const n of UNIT_OPTIONS) {
  const result = split(n);
  check(`${n} divides into a clean tenth`, Number.isInteger(result.fallen));
  check(`${n}: fallen plus survivors returns the unit`, result.fallen + result.survivors === n,
    `${result.fallen} + ${result.survivors} = ${n}`);
  check(`${n}: casualty rate is 10.0%`, pct(result.fallen, n) === 10,
    `${pct(result.fallen, n).toFixed(1)}%`);
  check(`${n}: survival rate is 90.0%`, pct(result.survivors, n) === 90,
    `${pct(result.survivors, n).toFixed(1)}%`);
}

const base = split(DEFAULT_UNIT);
check('default cohort has 48 selected', base.fallen === 48, String(base.fallen));
check('default cohort has 432 survivors', base.survivors === 432, String(base.survivors));
check('nine survivors per selected soldier', base.survivors / base.fallen === 9,
  `${base.survivors / base.fallen}:1`);

const broadAge = age(PUBLICATION_YEAR, BROAD_DECADE_START);
check('1660s lower-bound convention gives 366 years', broadAge === 366, String(broadAge));
check('366 rounds to about 360 years by decades', Math.floor(broadAge / 10) * 10 === 360);
check('literal c.1600 predates broad 1660s by about 60 years', BROAD_DECADE_START - LITERAL_YEAR === 60);
check('Cromwell tax date is 1655', TAX_YEAR === 1655);

const here = dirname(fileURLToPath(import.meta.url));
const htmlPath = join(here, '..', '..', 'public', 'strata', 'does-decimate-mean-one-in-ten', 'index.html');
let html = '';
try { html = readFileSync(htmlPath, 'utf8'); } catch {}
for (const token of ['48 fall', '432 walk away', '10.0%', '90.0%', '366 years', 'about 360 years',
  'c. 150 BCE', 'c. 1600', '1655', '1660s', 'as near as possible', 'prefers-reduced-motion',
  'role="status"', 'aria-live="polite"', '</script>', '</body>', '</html>']) {
  check(`page contains ${JSON.stringify(token)}`, html.includes(token));
}

const inline = html.match(/<script id="instrument-code">([\s\S]*?)<\/script>/);
check('instrument script exists and is closed', Boolean(inline));
check('page has no em dash characters', !html.includes('\u2014'));

console.log(`${passed} passed, ${failed} failed`);
process.exit(failed === 0 ? 0 : 1);
