import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import vm from 'node:vm';

const slug = 'the-six-thousand-votes-that-hurt';
const root = path.resolve(import.meta.dirname, '../..');
const htmlPath = path.join(root, 'public/strata', slug, 'index.html');
const mdPath = path.join(root, 'src/content/strata', `${slug}.md`);
const readmePath = path.join(root, 'research', slug, 'README.md');
const html = fs.readFileSync(htmlPath, 'utf8');
const frontmatter = fs.readFileSync(mdPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');
const visible = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ');

let passed = 0;
let failed = 0;
function check(name, condition, detail = '') {
  if (condition) {
    passed += 1;
    console.log(`PASS  ${name}${detail ? `  ${detail}` : ''}`);
  } else {
    failed += 1;
    console.error(`FAIL  ${name}${detail ? `  ${detail}` : ''}`);
  }
}
function equal(name, actual, expected) {
  const ok = JSON.stringify(actual) === JSON.stringify(expected);
  check(name, ok, `actual=${JSON.stringify(actual)} expected=${JSON.stringify(expected)}`);
}
function shows(label, computed, decimals) {
  const rendered = computed.toFixed(decimals);
  check(`page displays ${label} as ${rendered}`, visible.includes(rendered),
    `computed=${computed} rendered=${rendered}`);
  return rendered;
}

const profileMatch = html.match(/<script id="profile-data" type="application\/json">([^<]+)<\/script>/);
check('embedded profile payload exists', Boolean(profileMatch));
if (!profileMatch) process.exit(1);
const raw = JSON.parse(profileMatch[1]);
const expectedRaw = [
  ['B>Pn>P',27053], ['B>P>Pn',15467], ['B',11290],
  ['Pn>B>P',34049], ['Pn>P>B',3652], ['Pn',21272],
  ['P>B>Pn',47407], ['P>Pn>B',4645], ['P',23747]
];
equal('nine published profile columns are pinned', raw, expectedRaw);
const digest = crypto.createHash('sha256').update(JSON.stringify(raw)).digest('hex');
equal('profile SHA-256', digest, 'a7b9842897f81faa150aece1e71fa5bc24860c8fe4889376d929575208ffdc32');

const profile = raw.map(([code,count]) => ({ code, ranking:code.split('>'), count }));
const candidates = ['B','Pn','P'];
function expand(rows) {
  const ballots = [];
  for (const row of rows) {
    for (let i = 0; i < row.count; i += 1) ballots.push([...row.ranking]);
  }
  return ballots;
}
function countExpanded(ballots, active) {
  const counts = { B:0, Pn:0, P:0 };
  let inactive = 0;
  for (const ballot of ballots) {
    const choice = ballot.find(candidate => active.includes(candidate));
    if (choice) counts[choice] += 1;
    else inactive += 1;
  }
  return { counts, inactive };
}
function tabulateExpanded(rows) {
  const ballots = expand(rows);
  const first = countExpanded(ballots, candidates);
  const minimum = Math.min(...candidates.map(candidate => first.counts[candidate]));
  const tie = candidates.filter(candidate => first.counts[candidate] === minimum);
  if (tie.length !== 1) return { ballots:ballots.length, first, tie };
  const eliminated = tie[0];
  const active = candidates.filter(candidate => candidate !== eliminated);
  const final = countExpanded(ballots, active);
  const winner = final.counts[active[0]] > final.counts[active[1]] ? active[0] : active[1];
  return { ballots:ballots.length, first, eliminated, final, winner };
}

// This pattern-count route is deliberately separate from ballot expansion.
function tabulatePatterns(rows) {
  const first = { B:0, Pn:0, P:0 };
  let total = 0;
  for (const row of rows) {
    total += row.count;
    first[row.ranking[0]] += row.count;
  }
  const minimum = Math.min(first.B, first.Pn, first.P);
  const tie = candidates.filter(candidate => first[candidate] === minimum);
  if (tie.length !== 1) return { ballots:total, first:{ counts:first, inactive:0 }, tie };
  const eliminated = tie[0];
  const active = candidates.filter(candidate => candidate !== eliminated);
  const finalCounts = { B:0, Pn:0, P:0 };
  let inactive = 0;
  for (const row of rows) {
    const choice = row.ranking.find(candidate => active.includes(candidate));
    if (choice) finalCounts[choice] += row.count;
    else inactive += row.count;
  }
  const winner = finalCounts[active[0]] > finalCounts[active[1]] ? active[0] : active[1];
  return { ballots:total, first:{ counts:first, inactive:0 }, eliminated,
    final:{ counts:finalCounts, inactive }, winner };
}
function pairwiseExpanded(rows, a, b) {
  const ballots = expand(rows);
  let av = 0;
  let bv = 0;
  for (const ballot of ballots) {
    const ai = ballot.indexOf(a);
    const bi = ballot.indexOf(b);
    if (ai < 0 && bi < 0) continue;
    if (ai < 0) bv += 1;
    else if (bi < 0 || ai < bi) av += 1;
    else bv += 1;
  }
  return [av,bv];
}
function pairwiseColumns(c) {
  return {
    bp:[c[0]+c[1]+c[2]+c[3], c[4]+c[6]+c[7]+c[8]],
    bs:[c[0]+c[1]+c[2]+c[6], c[3]+c[4]+c[5]+c[7]],
    ps:[c[6]+c[7]+c[8]+c[1], c[3]+c[4]+c[5]+c[0]]
  };
}

const direct = tabulateExpanded(profile);
const independent = tabulatePatterns(profile);
equal('independent route total agrees', independent.ballots, direct.ballots);
equal('independent route first round agrees', independent.first.counts, direct.first.counts);
equal('independent route final round agrees', independent.final.counts, direct.final.counts);
equal('independent route elimination agrees', independent.eliminated, direct.eliminated);
equal('independent route winner agrees', independent.winner, direct.winner);

equal('official anchor, continuing first round', direct.ballots, 188582);
equal('official anchor, first choices',
  [direct.first.counts.B,direct.first.counts.Pn,direct.first.counts.P],
  [53810,58973,75799]);
equal('official anchor, eliminated candidate', direct.eliminated, 'B');
equal('official anchor, final choices',
  [direct.final.counts.P,direct.final.counts.Pn], [91266,86026]);
equal('official anchor, final continuing ballots',
  direct.final.counts.P + direct.final.counts.Pn, 177292);
equal('official reconciliation of grouped inactive ballots', 11243 + 47, 11290);

const c = raw.map(row => row[1]);
const columnPairs = pairwiseColumns(c);
const expandedPairs = {
  bp:pairwiseExpanded(profile,'B','P'),
  bs:pairwiseExpanded(profile,'B','Pn'),
  ps:pairwiseExpanded(profile,'P','Pn')
};
equal('independent pairwise route, Begich vs Peltola', expandedPairs.bp, columnPairs.bp);
equal('published anchor, Begich vs Peltola', expandedPairs.bp, [87859,79451]);
equal('independent pairwise route, Begich vs Palin', expandedPairs.bs, columnPairs.bs);
equal('published anchor, Begich vs Palin', expandedPairs.bs, [101217,63618]);
equal('independent pairwise route, Peltola vs Palin', expandedPairs.ps, columnPairs.ps);
equal('published anchor, Peltola vs Palin', expandedPairs.ps, [91266,86026]);
equal('pairwise margins',
  [87859-79451,101217-63618,91266-86026], [8408,37599,5240]);

function cloneProfile(rows) {
  return rows.map(row => ({ code:row.code, ranking:[...row.ranking], count:row.count }));
}
function monotonicProfile(k) {
  const rows = cloneProfile(profile);
  rows[5].count -= k;
  rows.push({ code:'P>Pn', ranking:['P','Pn'], count:k });
  return rows;
}
function noShowProfile(k) {
  const rows = cloneProfile(profile);
  rows[3].count -= k;
  return rows;
}
check('monotonicity source contains at least 6,000 ballots', profile[5].count >= 6000,
  `source=${profile[5].count}`);
check('no-show source contains at least 6,000 ballots', profile[3].count >= 6000,
  `source=${profile[3].count}`);

const mono6000 = tabulateExpanded(monotonicProfile(6000));
equal('6,000 moved, first choices',
  [mono6000.first.counts.B,mono6000.first.counts.Pn,mono6000.first.counts.P],
  [53810,52973,81799]);
equal('6,000 moved, Palin eliminated', mono6000.eliminated, 'Pn');
equal('6,000 moved, Begich defeats Peltola',
  [mono6000.final.counts.B,mono6000.final.counts.P], [87859,85451]);
equal('6,000 moved, winner', mono6000.winner, 'B');

const noShow6000 = tabulateExpanded(noShowProfile(6000));
equal('6,000 removed, first choices',
  [noShow6000.first.counts.B,noShow6000.first.counts.Pn,noShow6000.first.counts.P],
  [53810,52973,75799]);
equal('6,000 removed, Palin eliminated', noShow6000.eliminated, 'Pn');
equal('6,000 removed, Begich defeats Peltola',
  [noShow6000.final.counts.B,noShow6000.final.counts.P], [81859,79451]);
equal('6,000 removed, winner', noShow6000.winner, 'B');

let swept = 0;
for (let k = 0; k <= 6000; k += 1) {
  const mono = tabulatePatterns(monotonicProfile(k));
  const noShow = tabulatePatterns(noShowProfile(k));
  const expectedMonoFirst = [53810,58973-k,75799+k];
  const expectedNoShowFirst = [53810,58973-k,75799];
  const monoFirst = [mono.first.counts.B,mono.first.counts.Pn,mono.first.counts.P];
  const noShowFirst = [noShow.first.counts.B,noShow.first.counts.Pn,noShow.first.counts.P];
  if (JSON.stringify(monoFirst) !== JSON.stringify(expectedMonoFirst)) break;
  if (JSON.stringify(noShowFirst) !== JSON.stringify(expectedNoShowFirst)) break;
  if (k < 5163) {
    if (mono.eliminated !== 'B' || mono.winner !== 'P') break;
    if (noShow.eliminated !== 'B' || noShow.winner !== 'P') break;
    if (mono.final.counts.P !== 91266+k || mono.final.counts.Pn !== 86026-k) break;
    if (noShow.final.counts.P !== 91266 || noShow.final.counts.Pn !== 86026-k) break;
  } else if (k === 5163) {
    if (!mono.tie || !noShow.tie || mono.tie.length !== 2 || noShow.tie.length !== 2) break;
    if (mono.first.counts.B !== 53810 || mono.first.counts.Pn !== 53810) break;
  } else {
    if (mono.eliminated !== 'Pn' || mono.winner !== 'B') break;
    if (noShow.eliminated !== 'Pn' || noShow.winner !== 'B') break;
    if (mono.final.counts.B !== 87859 || mono.final.counts.P !== 79451+k) break;
    if (noShow.final.counts.B !== 87859-k || noShow.final.counts.P !== 79451) break;
  }
  swept += 1;
}
equal('all reader-reachable slider settings, including refusal, verify', swept, 6001);

const poisoned = cloneProfile(profile);
poisoned[0].count += 1;
const poisonedResult = tabulateExpanded(poisoned);
const poisonFailures = [
  poisonedResult.ballots !== 188582,
  poisonedResult.first.counts.B !== 53810
];
equal('control on the control rejects both poisoned anchors', poisonFailures, [true,true]);

const pinnedArxivMatch = readme.match(/`https:\/\/arxiv\.org\/abs\/(\d+\.\d+)`/);
check('pinned source supplies an arXiv identifier', Boolean(pinnedArxivMatch));
if (pinnedArxivMatch) {
  const renderedArxivId = shows('the pinned arXiv identifier', Number(pinnedArxivMatch[1]), 5);
  equal('the visible source list contains exactly that arXiv identifier',
    [...visible.matchAll(/arXiv:(\d+\.\d+)v3/g)].map(match => match[1]), [renderedArxivId]);
}

const rendered = {
  continuing:'188,582', 'r1-b':'53,810', 'r1-s':'58,973', 'r1-m':'75,799',
  'transfer-s':'27,053', 'transfer-m':'15,467', 'inactive-group':'11,290',
  'round2-continuing':'177,292 continuing', 'r2-s':'86,026', 'r2-m':'91,266',
  'official-margin':'5,240', 'official-exhausted':'11,243 exhausted',
  'official-overvote-transfer':'47 overvotes', p0:'27,053', p1:'15,467', p2:'11,290',
  p3:'34,049', p4:'3,652', p5:'21,272', p6:'47,407', p7:'4,645', p8:'23,747',
  'b-over-m':'87,859 Begich', 'm-over-b':'79,451 Peltola', 'b-m-margin':'8,408',
  'b-over-s':'101,217 Begich', 's-over-b':'63,618 Palin', 'b-s-margin':'37,599',
  'm-over-s':'91,266 Peltola', 's-over-m':'86,026 Palin', 'm-s-margin':'5,240',
  'condorcet-wins':'2 of 2', 'mono-k':'6,000', 'mono-b':'53,810', 'mono-s':'52,973',
  'mono-m':'81,799', 'mono-final':'87,859 to 85,451', 'mono-source':'21,272',
  'noshow-k':'6,000', 'noshow-b':'53,810', 'noshow-s':'52,973', 'noshow-m':'75,799',
  'noshow-final':'81,859 to 79,451', 'noshow-source':'34,049',
  'poisoned-column':'27,054', 'profile-hash':digest, 'tie-k':'5,163', 'tie-total':'53,810'
};
for (const [key,value] of Object.entries(rendered)) {
  const re = new RegExp(`data-figure="${key}"[^>]*>\\s*${value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')}\\s*<`);
  check(`rendered figure ${key}`, re.test(html));
}

const dek = "Recount the official totals from Alaska's 2022 special House election through a published reduction of its scanned-ballot record. Mary Peltola won the instant runoff, while Nick Begich beat both rivals head to head. Then operate two 6,000-ballot counterfactuals: extra first-choice support makes Peltola lose, and voters who rank Begich above Peltola obtain that outcome by abstaining. Every total is recomputed in the browser, with the reduction's limits visible.";
check('frontmatter date', /\ndate: 2026-08-25\n/.test(frontmatter));
check('frontmatter draft false', /\ndraft: false\n/.test(frontmatter));
check('frontmatter seam is closed-vocabulary commons', /\nseam: "commons"\n/.test(frontmatter));
check('frontmatter dek matches the verified page', frontmatter.includes(`dek: "${dek}"`));
check('meta description matches frontmatter dek', html.includes(`<meta name="description" content="${dek}" />`));
check('SEO title is honest and shared',
  html.includes('<title>Recounting the 2022 Alaska Ranked Choice Election Through a Published Reduction</title>') &&
  frontmatter.includes('seoTitle: "Recounting the 2022 Alaska Ranked Choice Election Through a Published Reduction"'));
check('canonical URL', html.includes('https://artwaste.land/strata/the-six-thousand-votes-that-hurt/'));
check('exact pairwise figures are attributed to Graham-Squire and McCune',
  html.includes('The exact figures below come from the nine-pattern reduction published by Adam\n        Graham-Squire and David McCune.'));
check('exact pairwise figures reject official and raw-CVR labels',
  html.includes('They are not official Alaska pairwise tabulation totals and\n        not totals from a direct replay of the raw CVR export.'));

const jsonLdMatch = html.match(/<script type="application\/ld\+json">([^<]+)<\/script>/);
check('JSON-LD exists', Boolean(jsonLdMatch));
if (jsonLdMatch) {
  const article = JSON.parse(jsonLdMatch[1]);
  equal('JSON-LD type', article['@type'], 'Article');
  equal('JSON-LD name', article.name,
    'Recounting the 2022 Alaska Ranked Choice Election Through a Published Reduction');
  equal('JSON-LD datePublished', article.datePublished, '2026-08-25');
  equal('JSON-LD dateModified', article.dateModified, '2026-08-25');
  equal('JSON-LD description', article.description, dek);
}

const plainMatch = frontmatter.match(/\nplain: "([^"]+)"\n/);
check('plain placard is one double-quoted line', Boolean(plainMatch));
if (plainMatch) {
  check('plain placard length is 90 to 420', plainMatch[1].length >= 90 && plainMatch[1].length <= 420,
    `length=${plainMatch[1].length}`);
  check('plain placard has at most three sentences', (plainMatch[1].match(/[.!?](?:\s|$)/g) || []).length <= 3);
}

for (const related of ['the-only-fair-vote','any-loop-you-can-draw','the-vote-that-never-counted']) {
  check(`related target exists: ${related}`, fs.existsSync(path.join(root,'src/content/strata',`${related}.md`)));
}
check('all relates entries are objects', (frontmatter.match(/\n  - to:/g) || []).length === 3);
check('README names CVR scan and hand-count limit', readme.includes('scanned ballots, not ballots counted only by hand'));
check('README names the raw ZIP retrieval failure', readme.includes('CloudFront CAPTCHA'));
check('README does not claim a raw ZIP hash', readme.includes('no SHA-256 for that ZIP is claimed'));

const authored = [html,frontmatter,readme,fs.readFileSync(import.meta.filename,'utf8')].join('\n');
check('no em dash in any authored artifact', !authored.includes('\u2014'));
check('required closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
check('reduced-motion guard is present', html.includes('(prefers-reduced-motion: reduce)'));
check('live status regions are present', /role="status"[^>]*aria-live="polite"/.test(html));
check('visible focus style is present', html.includes(':focus-visible'));

const executableScripts = [...html.matchAll(/<script(?:\s[^>]*)?>([\s\S]*?)<\/script>/g)]
  .filter(match => match[1].trim() && !match[0].includes('application/ld+json') && !match[0].includes('application/json'));
check('one inline executable script found', executableScripts.length === 1);
for (const [index,script] of executableScripts.entries()) {
  let syntaxOK = true;
  try { new vm.Script(script[1], { filename:`inline-${index}.js` }); }
  catch (error) { syntaxOK = false; console.error(error.message); }
  check(`inline script ${index + 1} parses`, syntaxOK);
}

console.log(`\n${passed} passed, ${failed} failed.`);
if (failed) process.exit(1);
