// verify-pigment-that-wasnt-born.mjs: the material-milestone comparison.
// Run: node research/pigment-that-wasnt-born/verify-pigment-that-wasnt-born.mjs
// This standalone check compares stored dates and recomputes four model cases.
// It cannot verify historical evidence, first existence, public availability,
// original paint layers, or agreement with an independently edited page.
// A date flag is milestone_year > claimed_year, not an automatic conviction.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};

const SCALE_MIN = 1600;            // left edge of the visible timeline
const VERMEER_DIED = 1675;         // Johannes Vermeer, 1632–1675 (Delft)

// Milestones: WebExhibits histories of cobalt blue, ultramarine and zinc white.
//   year = selected documented milestone (pre-1600 rows use the display bound)
//   lo,hi = span across named milestones, not invention-date confidence bounds
//   ancient = predates the timeline entirely (drawn from the left edge)
const PIGS = {
  leadwhite:  { name: 'Lead white',            year: 1600,  lo: null, hi: null, ancient: true },
  lapis:      { name: 'Ultramarine (lapis)',   year: 1600,  lo: null, hi: null, ancient: true },
  vermilion:  { name: 'Vermilion',             year: 1600,  lo: null, hi: null, ancient: true },
  ochre:      { name: 'Yellow ochre',          year: 1600, lo: null, hi: null, ancient: true },
  bone:       { name: 'Bone black',            year: 1600, lo: null, hi: null, ancient: true },
  prussian:   { name: 'Prussian blue',         year: 1704,  lo: 1704, hi: 1710, ancient: false },
  cobalt:     { name: 'Cobalt blue',           year: 1777,  lo: 1777, hi: 1807, ancient: false },
  synthultra: { name: 'Synthetic ultramarine', year: 1826,  lo: 1826, hi: 1830, ancient: false },
  zincwhite:  { name: 'Zinc white',            year: 1782,  lo: 1782, hi: 1850, ancient: false },
  titanium:   { name: 'Titanium white',        year: 1916,  lo: 1916, hi: 1921, ancient: false },
  bakelite:   { name: 'Bakelite resin',   year: 1907,  lo: 1907, hi: 1909, ancient: false },
};

// ── The cases the page can load (must match the page's CASES exactly) ────────
const CASES = [
  { id: 'adulteress',  claim: 1665, pigs: ['leadwhite', 'lapis', 'vermilion', 'ochre', 'cobalt', 'bakelite'] },
  { id: 'procuress',   claim: 1622, pigs: ['leadwhite', 'lapis', 'ochre', 'bone', 'bakelite'] },
  { id: 'realvermeer', claim: 1665, pigs: ['leadwhite', 'lapis', 'vermilion', 'ochre', 'bone'] },
  { id: 'modern',      claim: 1660, pigs: ['leadwhite', 'synthultra', 'zincwhite', 'titanium', 'ochre'] },
];

// The comparison rule, recomputed here.
const isFlagged = (pigKey, year) => PIGS[pigKey].year > year;

// Check internal consistency of the stored milestone spans.
console.log('\n: stored material milestones and spans :');
for (const [k, p] of Object.entries(PIGS)) {
  if (p.ancient) {
    console.log(`  ··  ${p.name.padEnd(24)} known before 1600 (display bound ${p.year})`);
    ok(`${p.name} uses the pre-1600 display bound`, p.year === SCALE_MIN);
  } else {
    ok(`${p.name.padEnd(24)} year=${p.year} within range ${p.lo}–${p.hi}`,
       p.year === p.lo && p.lo <= p.hi, `(selected milestone; not proof of first existence)`);
  }
}

// Assert the dates transcribed from the cited histories; no live source verification.
console.log('\n: the cited milestone dates :');
ok('Cobalt aluminate documented in 1777 (WebExhibits)',          PIGS.cobalt.year === 1777);
ok('Cobalt blue French commercial production by 1807',       PIGS.cobalt.hi === 1807);
ok('Synthetic ultramarine: Guimet prize 1828',              PIGS.synthultra.year <= 1828 && PIGS.synthultra.hi >= 1828);
ok('Prussian blue c.1704 (Diesbach)',                        PIGS.prussian.year === 1704);
ok('Zinc oxide proposed as a white pigment in 1782 (WebExhibits)',      PIGS.zincwhite.year === 1782);
ok('Titanium white commercial-production milestone 1916',                   PIGS.titanium.year === 1916);
ok('Bakelite: filed 1907, patent 1909',                      PIGS.bakelite.year === 1907 && PIGS.bakelite.hi === 1909);

// Compare the selected milestones with Vermeer's death year.
console.log('\n: Vermeer died 1675: which selected material milestones flag the date :');
const modernPigs = Object.keys(PIGS).filter((k) => !PIGS[k].ancient);
for (const k of modernPigs) {
  const flagged = isFlagged(k, VERMEER_DIED);
  console.log(`  ${PIGS[k].name.padEnd(24)} year ${PIGS[k].year} → ${flagged ? 'later milestone' : 'no flag'}`);
}
ok('all selected modern milestones flag a 1675 claim',
   modernPigs.every((k) => isFlagged(k, VERMEER_DIED)));
ok('pre-1600 materials do not flag a 1675 claim',
   Object.keys(PIGS).filter((k) => PIGS[k].ancient).every((k) => !isFlagged(k, VERMEER_DIED)));

// Recompute each illustrative case against its separately asserted expected set.
// Expected model sets, not independent laboratory measurements.
const EXPECTED = {
  adulteress:  { flaggedDate: true,  flagged: ['cobalt', 'bakelite'] },
  procuress:   { flaggedDate: true,  flagged: ['bakelite'] },
  realvermeer: { flaggedDate: false, flagged: [] },
  modern:      { flaggedDate: true,  flagged: ['synthultra', 'zincwhite', 'titanium'] },
};

console.log('\n: recomputing each case from the rule :');
for (const c of CASES) {
  const flagged = c.pigs.filter((k) => isFlagged(k, c.claim));
  const flaggedDate = flagged.length > 0;
  const exp = EXPECTED[c.id];
  const setEq = flagged.length === exp.flagged.length &&
                flagged.every((k) => exp.flagged.includes(k));
  const names = flagged.map((k) => `${PIGS[k].name}(${PIGS[k].year})`).join(', ') || 'none';
  console.log(`  ${c.id.padEnd(12)} claim=${c.claim}  →  ` +
              `${flaggedDate ? 'DATE FLAG' : 'no flag'}  flagged: ${names}`);
  ok(`${c.id.padEnd(12)} date flag matches expected model`, flaggedDate === exp.flaggedDate);
  ok(`${c.id.padEnd(12)} flagged set matches expected model`, setEq,
     `got [${flagged.join(',')}] expected [${exp.flagged.join(',')}]`);
}

// The four default model outcomes.
console.log('\n: the default date flags :');
ok('Christ with the Adulteress (claim 1665): cobalt milestone 1777 > 1665',
   isFlagged('cobalt', 1665), `1777 > 1665`);
ok('Christ with the Adulteress (claim 1665): Bakelite milestone 1907 > 1665',
   isFlagged('bakelite', 1665), `1907 > 1665`);
ok('The Procuress (claim 1622): Bakelite milestone 1907 > 1622',
   isFlagged('bakelite', 1622), `1907 > 1622`);
ok('The illustrative Vermeer palette at 1665 has no later milestones',
   CASES[2].pigs.every((k) => !isFlagged(k, 1665)));

// And the monotonicity the slider relies on: drag the claim later and flags only
// ever disappear (a milestone in year Y stops flagging once claim >= Y).
console.log('\n: slider monotonicity: later claim ⇒ never more flags :');
{
  let monotone = true;
  for (const c of CASES) {
    let prev = Infinity;
    for (let y = 1600; y <= 2026; y++) {
      const n = c.pigs.filter((k) => isFlagged(k, y)).length;
      if (n > prev) { monotone = false; break; }
      prev = n;
    }
  }
  ok('flag count is non-increasing as the claimed year advances', monotone);
}

// Earlier evidence must not receive the old false-impossibility flags.
console.log('\n: earlier-evidence and boundary regressions :');
for (const [key, before, at, after] of [
  ['cobalt', 1776, 1777, 1780],
  ['synthultra', 1825, 1826, 1827],
  ['zincwhite', 1781, 1782, 1800],
]) {
  ok(`${key}: flags before selected milestone (not proof of impossibility)`, isFlagged(key, before));
  ok(`${key}: no flag at selected milestone`, !isFlagged(key, at));
  ok(`${key}: no flag at earlier-evidence regression year ${after}`, !isFlagged(key, after));
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
