#!/usr/bin/env node
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const slug = 'the-date-made-from-one-word-twice';
const htmlPath = path.join(root, 'public/strata', slug, 'index.html');
const mdPath = path.join(root, 'src/content/strata', `${slug}.md`);
const readmePath = path.join(here, 'README.md');
const html = fs.readFileSync(htmlPath, 'utf8');
const md = fs.readFileSync(mdPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');
const text = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ');
let checks = 0;
let failed = 0;

function check(label, ok, detail = '') {
  checks++;
  if (!ok) failed++;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${label}${detail ? ` | ${detail}` : ''}`);
}
function eq(label, actual, expected) {
  check(label, Object.is(actual, expected), `actual=${actual} expected=${expected}`);
}
function extractScript(type, id = null) {
  const idPart = id ? `(?=[^>]*\\bid=["']${id}["'])` : '';
  const escapedType = type.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const re = new RegExp(`<script${idPart}(?=[^>]*\\btype=["']${escapedType}["'])[^>]*>([\\s\\S]*?)<\\/script>`, 'i');
  const hit = html.match(re);
  if (!hit) throw new Error(`Missing script block: ${type} ${id || ''}`);
  return hit[1].trim();
}
const data = JSON.parse(extractScript('application/json', 'stratum-data'));
const jsonLd = JSON.parse(extractScript('application/ld+json'));

function independentWitness(w) {
  return Boolean(w.day && w.month && w.dayToken && w.monthToken && w.dayToken !== w.monthToken);
}
function phraseSupport(day, month) {
  return data.witnesses.filter(w => independentWitness(w) && w.day === day && w.month === month).length;
}
function exactLiteralSupport(literal) {
  let n = 0;
  for (const w of data.witnesses) if (w.literal === literal) n++;
  return n;
}

console.log('\nMANUSCRIPT TOKEN CHECK');
eq('primary route finds zero independent nonum plus Novembres readings', phraseSupport('nonum', 'Novembres'), 0);
eq('independent exact-phrase route also finds zero', exactLiteralSupport('nonum Kal. Novembres'), 0);
eq('displayed excerpt has one complete old September reading', phraseSupport('nono', 'Septembres'), 1);
const poisonedWitness = { day:'nonum', month:'Novembres', dayToken:'same-token', monthToken:'same-token' };
check('CONTROL ON THE CONTROL rejects one token reused in two slots', !independentWitness(poisonedWitness), 'poisoned ids=same-token/same-token');

const monthLengths = [31,28,31,30,31,30,31,31,30,31,30,31];
function decrement(month, day) {
  day--;
  if (day === 0) {
    month--;
    if (month === 0) month = 12;
    day = monthLengths[month - 1];
  }
  return [month, day];
}
function romanInclusiveBySteps(ordinal, kalendsMonth) {
  let month = kalendsMonth;
  let day = 1;
  for (let i = 1; i < ordinal; i++) [month, day] = decrement(month, day);
  return { month, day };
}
const oct24 = romanInclusiveBySteps(9, 11);
const aug24 = romanInclusiveBySteps(9, 9);
eq('independent backward enumeration puts nonum Kal. Novembres in October', oct24.month, 10);
eq('independent backward enumeration puts it on day 24', oct24.day, 24);
eq('published complete September phrase converts to August 24', `${aug24.month}-${aug24.day}`, '8-24');
const exclusivePoison = romanInclusiveBySteps(10, 11);
check('CONTROL ON THE CONTROL rejects ordinary nine-day subtraction', !(exclusivePoison.month === 10 && exclusivePoison.day === 24), `poisoned result=${exclusivePoison.month}-${exclusivePoison.day}`);

function leapYearsBefore(year) {
  const y = year - 1;
  return Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
}
function civilOrdinal(iso) {
  const [year, month, day] = iso.split('-').map(Number);
  const beforeMonth = [0,31,59,90,120,151,181,212,243,273,304,334][month - 1];
  const leapDay = month > 2 && (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 1 : 0;
  return 365 * (year - 1) + leapYearsBefore(year) + beforeMonth + leapDay + day;
}
function elapsedDays(a, b) { return civilOrdinal(b) - civilOrdinal(a); }

console.log('\nREPLICATION CALENDAR CHECK');
eq('published photography-session anchor count', data.sessions.length, 12);
eq('published session anchor starts 2023-10-17', data.sessions[0], '2023-10-17');
eq('published session anchor ends 2024-08-24', data.sessions.at(-1), '2024-08-24');
eq('independent Gregorian ordinal route gives 312 elapsed days', elapsedDays(data.sessions[0], data.sessions.at(-1)), 312);
eq('published plates yield ten unique frames used by scrubber', data.frames.length, 10);
const omitted = data.sessions.filter(s => !data.frames.some(f => f.date === s));
eq('scrubber discloses two listed sessions without unique plate frames', omitted.join(','), '2024-02-17,2024-06-17');
const poisonedSessions = data.sessions.slice(0, -1);
check('CONTROL ON THE CONTROL rejects a truncated session series', elapsedDays(poisonedSessions[0], poisonedSessions.at(-1)) !== 312, `poisoned elapsed=${elapsedDays(poisonedSessions[0], poisonedSessions.at(-1))}`);

function sha256(buf) { return crypto.createHash('sha256').update(buf).digest('hex'); }
function imageBlock(id) {
  return Buffer.from(extractScript('application/octet-stream', id).replace(/\s/g, ''), 'base64');
}
const imageBuffers = { montage:imageBlock('photo-montage'), pair:imageBlock('photo-pair') };
eq('embedded figure 4 crop image hash', sha256(imageBuffers.montage), '736e81f8320b00ed7071553314a96b854e2adabc6e02bc608664ed7f699ec04f');
eq('embedded figure 5 crop image hash', sha256(imageBuffers.pair), '42f94fa9ba500641625322d9db5a13500aeb78c4e7e9c87a3ca758e80a94d62b');

const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'aw-pompeii-verify-'));
try {
  const imagePaths = {};
  for (const [name, buf] of Object.entries(imageBuffers)) {
    imagePaths[name] = path.join(tmp, `${name}.jpg`);
    fs.writeFileSync(imagePaths[name], buf);
  }
  const convertProbe = spawnSync('convert', ['-version'], { encoding:'utf8' });
  check('ImageMagick is available for independent pixel decoding', convertProbe.status === 0, (convertProbe.stdout || convertProbe.stderr).split('\n')[0]);

  function framePixels(frame) {
    const [x,y,w,h] = frame.crop;
    const out = spawnSync('convert', [imagePaths[frame.source], '-crop', `${w}x${h}+${x}+${y}`, '+repage', '-filter', 'Point', '-resize', '600x420!', '-colorspace', 'sRGB', '-depth', '8', 'rgb:-'], { encoding:null, maxBuffer:3_000_000 });
    if (out.status !== 0) throw new Error(`ImageMagick failed: ${String(out.stderr)}`);
    if (out.stdout.length !== 600 * 420 * 3) throw new Error(`Unexpected RGB size ${out.stdout.length}`);
    return out.stdout;
  }
  function percentile(sorted, q) { return sorted[Math.ceil(sorted.length * q) - 1]; }
  function robustContrast(rgb) {
    const luma = [];
    for (let i = 0; i < rgb.length; i += 3) luma.push(Math.round(.2126 * rgb[i] + .7152 * rgb[i + 1] + .0722 * rgb[i + 2]));
    const sorted = luma.sort((a,b) => a-b);
    const p10 = percentile(sorted, .1);
    const p90 = percentile(sorted, .9);
    return { p10, p90, value:100 * (p90 - p10) / (p90 + p10) };
  }
  console.log('\nINDEPENDENT PHOTO DIAGNOSTIC');
  const metrics = data.frames.map((frame, i) => {
    const metric = robustContrast(framePixels(frame));
    console.log(`FRAME ${String(i + 1).padStart(2, '0')}  ${frame.date}  ${elapsedDays(data.sessions[0], frame.date)} days  ${metric.value.toFixed(1)} C  P10=${metric.p10} P90=${metric.p90}`);
    eq(`frame ${i + 1} rendered one-decimal contrast figure`, Number(metric.value.toFixed(1)), frame.expectedContrast);
    return metric;
  });
  check('all ten printed frames decode and produce finite contrast', metrics.length === 10 && metrics.every(m => Number.isFinite(m.value)));
  const poisonRgb = Buffer.alloc(600 * 420 * 3, 128);
  const poisonMetric = robustContrast(poisonRgb).value;
  check('CONTROL ON THE CONTROL rejects a deliberately flattened photograph', poisonMetric < metrics[0].value * .5, `real=${metrics[0].value.toFixed(1)} C poison=${poisonMetric.toFixed(1)} C`);
} finally {
  fs.rmSync(tmp, { recursive:true, force:true });
}

console.log('\nCLUE SCORE CHECK');
const scoreCounts = [0,1,2].map(score => data.clues.filter(c => c.score === score).length);
eq('six autumn clues are scored', data.clues.length, 6);
eq('score distribution is four unbounded, two conditional, zero secure', scoreCounts.join(','), '4,2,0');
check('every clue names its bound and reason', data.clues.every(c => c.bound.length > 10 && c.why.length > 30));
check('scores are categories rather than probabilities', data.clues.every(c => Number.isInteger(c.score) && c.score >= 0 && c.score <= 2));

console.log('\nSHAREABLE SURFACE CHECK');
eq('JSON-LD Article type', jsonLd['@type'], 'Article');
eq('JSON-LD publication date', jsonLd.datePublished, '2026-08-25');
eq('JSON-LD modification date', jsonLd.dateModified, '2026-08-25');
check('search title asks rather than declares', html.includes('<title>Did Vesuvius Erupt on October 24, 79 CE?</title>'));
check('meta description says the exact day remains unestablished', html.includes("neither October 24 nor August 24 is established as the eruption's exact day"));
check('frontmatter title matches H1', md.includes('title: "The Date Made From One Word Twice"') && html.includes('<h1>The Date Made From One Word Twice</h1>'));
check('frontmatter placard names the verified 312-day result', md.includes('across 312 days'));
check('rendered prose contains the recomputed 312-day figure', html.includes('<strong id="elapsed-prose">312 days</strong>'));
check('rendered Foss citation preserves the source-page range pinned in the research record', text.includes('pages 128 to 132') && readme.includes('pages 128 to 132'));
check('rendered check exposes independent route, anchor, and poison control', html.includes('independent route: October 24 manuscript support is zero') && html.includes('published anchor: the Park paper lists 12 photo sessions') && html.includes('control on the control rejects a duplicated physical token'));
check('rendered check binds live photo output to verifier figures', html.includes('rendered photo figures match the independent verifier') && html.includes("m.value.toFixed(1) === DATA.frames[i].expectedContrast.toFixed(1)"));
check('page discloses diagnostic free choices', html.includes('the crop coordinates, and the P10/P90 contrast diagnostic'));
check('page does not claim October 24 or August 24 is correct', !/October 24 is the (correct|true) date|August 24 is the (correct|true) date/i.test(html));
check('no third-party subresource URL appears', !/(?:src|srcset)=["']https?:\/\//i.test(html));
check('required closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
check('no em dash appears in authored artifacts', !html.includes('—') && !md.includes('—'));

const optionalPdf = '/tmp/pompeii-date-paper.pdf';
if (fs.existsSync(optionalPdf)) {
  const hash = sha256(fs.readFileSync(optionalPdf));
  eq('optional downloaded official PDF matches pinned SHA-256', hash, 'c21252e6d54e71be82b5c26463895a347ceabfa9a0447acbeee3b6b9201a28c0');
} else {
  console.log(`SKIP  optional source PDF hash | download to ${optionalPdf} to check provenance`);
}

console.log(`\n${failed ? 'FAIL' : 'PASS'}  ${checks - failed}/${checks} assertions passed`);
if (failed) process.exit(1);
