#!/usr/bin/env node

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const HTML_PATH = path.join(ROOT, 'public/strata/the-color-that-was-not-a-temperature/index.html');
const MD_PATH = path.join(ROOT, 'src/content/strata/the-color-that-was-not-a-temperature.md');

// CIE 1931 2 degree observer and CIE illuminant C, sampled every 10 nm.
// Values are the abridged tables in CIE 15:2004. Fujimura used illuminant C.
const SPECTRAL = [
  [380,.001368,.000039,.00645,33.00],[390,.004243,.000120,.02005,47.40],
  [400,.014310,.000396,.06785,63.30],[410,.043510,.001210,.20740,80.60],
  [420,.134380,.004000,.64560,98.10],[430,.283900,.011600,1.38560,112.40],
  [440,.348280,.023000,1.74706,121.50],[450,.336200,.038000,1.77211,124.00],
  [460,.290800,.060000,1.66920,123.10],[470,.195360,.090980,1.28764,123.80],
  [480,.095640,.139020,.81295,123.90],[490,.032010,.208020,.46518,120.70],
  [500,.004900,.323000,.27200,112.10],[510,.009300,.503000,.15820,102.30],
  [520,.063270,.710000,.07825,96.90],[530,.165500,.862000,.04216,98.00],
  [540,.290400,.954000,.02030,102.10],[550,.433450,.994950,.00875,105.20],
  [560,.594500,.995000,.00390,105.30],[570,.762100,.952000,.00210,102.30],
  [580,.916300,.870000,.00165,97.80],[590,1.026300,.757000,.00110,93.20],
  [600,1.062200,.631000,.00080,89.70],[610,1.002600,.503000,.00034,88.40],
  [620,.854450,.381000,.00019,88.10],[630,.642400,.265000,.00005,88.00],
  [640,.447900,.175000,.00002,87.80],[650,.283500,.107000,0,88.20],
  [660,.164900,.061000,0,87.90],[670,.087400,.032000,0,86.30],
  [680,.046770,.017000,0,84.00],[690,.022700,.008210,0,80.20],
  [700,.011359,.004102,0,76.30],[710,.005790,.002091,0,72.00],
  [720,.002899,.001047,0,68.30],[730,.001440,.000520,0,64.40],
  [740,.000690,.000249,0,61.50],[750,.000332,.000120,0,59.20],
  [760,.000166,.000060,0,58.10],[770,.000083,.000030,0,58.20],
  [780,.000042,.000015,0,59.10]
];

// Fujimura 1972, table 2. These are measured x,y,Y values and the film
// thickness assigned in the paper. Points at 100 nm and above are excluded.
const FUJIMURA = [
  [0,.299,.306,25],[6,.322,.328,21],[11,.335,.348,17],[19,.362,.367,14],
  [26,.388,.384,14],[32,.393,.356,7.2],[35,.365,.316,5.2],[38,.320,.273,4.1],
  [41,.281,.238,4.7],[44,.255,.214,4.0],[54,.219,.221,5.3],[56,.235,.239,6.6],
  [64,.242,.261,14],[73,.265,.287,14],[81,.286,.308,19],[87,.309,.323,20],
  [89,.307,.321,20],[94,.316,.331,27],[98,.324,.337,23]
];

// McAdam and Geil 1939, table 2 supplies n. Temperatures at 100,000 minutes
// were read from figures 16 to 18. The digitization uncertainty is +/- 10 C.
const THERMAL = {
  straw: { iron: { n:30.0, cAt1e5:68 }, chromium: { n:23.0, cAt1e5:150 } },
  brown: { iron: { n:30.4, cAt1e5:120 }, chromium: { n:33.1, cAt1e5:440 } },
  blue:  { iron: { n:31.1, cAt1e5:164 }, chromium: { n:34.3, cAt1e5:500 } }
};

function complex(re, im) { return { re, im }; }
function add(a,b) { return complex(a.re+b.re,a.im+b.im); }
function mul(a,b) { return complex(a.re*b.re-a.im*b.im,a.re*b.im+a.im*b.re); }
function div(a,b) {
  const q=b.re*b.re+b.im*b.im;
  return complex((a.re*b.re+a.im*b.im)/q,(a.im*b.re-a.re*b.im)/q);
}
function abs2(a) { return a.re*a.re+a.im*a.im; }
function expi(a) { const e=Math.exp(-a.im); return complex(e*Math.cos(a.re),e*Math.sin(a.re)); }

function constants(lambda) {
  const q=lambda/100;
  return {
    n0:1,
    n1:2.42,
    k1:1.2300-.1555*q+.0066*q*q,
    n2:-1.2215+.94313*q-.054766*q*q,
    k2:.4165+.7768*q-.0476*q*q
  };
}

// Route 1: recursive complex-amplitude Fresnel reflection.
function reflectanceFresnel(lambda, thickness, poison=false) {
  const o=constants(lambda);
  const N0=complex(o.n0,0), N1=complex(o.n1, poison ? -o.k1 : o.k1), N2=complex(o.n2,o.k2);
  const r01=div(add(N0,complex(-N1.re,-N1.im)),add(N0,N1));
  const r12=div(add(N1,complex(-N2.re,-N2.im)),add(N1,N2));
  const beta=complex(2*Math.PI*N1.re*thickness/lambda,2*Math.PI*N1.im*thickness/lambda);
  const phase=expi(complex(2*beta.re,2*beta.im));
  const numerator=add(r01,mul(r12,phase));
  const denominator=add(complex(1,0),mul(mul(r01,r12),phase));
  return abs2(div(numerator,denominator));
}

// Route 2: Fujimura's printed Heavens closed form, his equation 3.
function reflectanceHeavens(lambda, thickness) {
  const {n0,n1,k1,n2,k2}=constants(lambda);
  const d1=(n0+n1)**2+k1**2;
  const d2=(n1+n2)**2+(k1+k2)**2;
  const g1=(n0*n0-n1*n1-k1*k1)/d1;
  const h1=2*n0*k1/d1;
  const g2=(n1*n1-n2*n2+k1*k1-k2*k2)/d2;
  const h2=2*(n1*k2-n2*k1)/d2;
  const A=2*(g1*g2+h1*h2), B=2*(g1*h2-g2*h1);
  const C=2*(g1*g2-h1*h2), D=2*(g1*h2+g2*h1);
  const a=2*Math.PI*k1*thickness/lambda;
  const gamma=2*Math.PI*n1*thickness/lambda;
  const numerator=(g1*g1+h1*h1)*Math.exp(2*a)+(g2*g2+h2*h2)*Math.exp(-2*a)+A*Math.cos(2*gamma)+B*Math.sin(2*gamma);
  const denominator=Math.exp(2*a)+(g1*g1+h1*h1)*(g2*g2+h2*h2)*Math.exp(-2*a)+C*Math.cos(2*gamma)+D*Math.sin(2*gamma);
  return numerator/denominator;
}

function xyzFor(thickness, route=reflectanceFresnel) {
  let X=0,Y=0,Z=0,whiteY=0;
  for (const [lambda,x,y,z,illum] of SPECTRAL) {
    const r=route(lambda,thickness);
    X+=r*illum*x; Y+=r*illum*y; Z+=r*illum*z; whiteY+=illum*y;
  }
  return {X:X/whiteY,Y:Y/whiteY,Z:Z/whiteY};
}
function xy({X,Y,Z}) { const s=X+Y+Z; return {x:X/s,y:Y/s}; }
function xyzFromXyY(xv,yv,Y) { return {X:xv*Y/yv,Y,Z:(1-xv-yv)*Y/yv}; }
function lab(v,white) {
  const f=t=>t>216/24389?Math.cbrt(t):(24389/27*t+16)/116;
  const fx=f(v.X/white.X), fy=f(v.Y/white.Y), fz=f(v.Z/white.Z);
  return {L:116*fy-16,a:500*(fx-fy),b:200*(fy-fz)};
}
function de76(a,b) { return Math.hypot(a.L-b.L,a.a-b.a,a.b-b.b); }
function whiteXYZ() {
  let X=0,Y=0,Z=0;
  for (const [,x,y,z,illum] of SPECTRAL) { X+=illum*x; Y+=illum*y; Z+=illum*z; }
  return {X:X/Y,Y:1,Z:Z/Y};
}
function temperatureC(model,minutes) {
  return (model.cAt1e5+273.15)*Math.pow(100000/minutes,1/model.n)-273.15;
}
function fmt(n,d=3) { return Number(n).toFixed(d); }

const checks=[];
function check(name,pass,detail) { checks.push({name,pass,detail}); }

const sampleThickness=54;
const primary=xyzFor(sampleThickness,reflectanceFresnel);
const independent=xyzFor(sampleThickness,reflectanceHeavens);
const pxy=xy(primary), ixy=xy(independent);
const routeGap=Math.max(...SPECTRAL.map(([l])=>Math.abs(reflectanceFresnel(l,sampleThickness)-reflectanceHeavens(l,sampleThickness))));
check('independent optical routes agree',routeGap<1e-12 && Math.hypot(pxy.x-ixy.x,pxy.y-ixy.y)<1e-12,
  `54 nm: max spectral |delta R| ${routeGap.toExponential(2)}; xy gap ${Math.hypot(pxy.x-ixy.x,pxy.y-ixy.y).toExponential(2)}`);

const white=whiteXYZ(), whitexy=xy(white);
check('published illuminant C white point is recovered',Math.abs(whitexy.x-.3101)<.0015 && Math.abs(whitexy.y-.3162)<.0015,
  `perfect reflector gives x=${fmt(whitexy.x,4)}, y=${fmt(whitexy.y,4)}; published C is 0.3101, 0.3162`);

let poisonPeak=0;
for (let d=10;d<=100;d+=5) for (const [l] of SPECTRAL) poisonPeak=Math.max(poisonPeak,reflectanceFresnel(l,d,true));
check('checker rejects a gain-film poison',poisonPeak>1.05,`reversing the absorption sign reaches R=${fmt(poisonPeak,3)}, above the passive limit 1`);

const deltas=[];
for (const [d,xv,yv,Ypct] of FUJIMURA) {
  const predicted=lab(xyzFor(d),white);
  const observed=lab(xyzFromXyY(xv,yv,Ypct/100),white);
  deltas.push(de76(predicted,observed));
}
const rmsDE=Math.sqrt(deltas.reduce((a,b)=>a+b*b,0)/deltas.length);
const maxDE=Math.max(...deltas);
check('Fujimura measured chromaticities stay near the historical single-film locus below 100 nm',rmsDE<35,
  `19 measured x,y,Y points: RMS Delta E76 ${fmt(rmsDE,1)}, maximum ${fmt(maxDE,1)}; thicknesses were assigned through the model`);

const visible= SPECTRAL.map(([l])=>reflectanceFresnel(l,sampleThickness));
const minR=Math.min(...visible), maxR=Math.max(...visible);
check('passive spectral bounds hold',minR>=0 && maxR<=1,`54 nm spectrum spans R=${fmt(minR,3)} to ${fmt(maxR,3)}`);

for (const key of Object.keys(THERMAL)) {
  for (const alloy of ['iron','chromium']) {
    const model=THERMAL[key][alloy];
    const t1=10,t2=1e6,T1=temperatureC(model,t1)+273.15,T2=temperatureC(model,t2)+273.15;
    const recovered=Math.log(t2/t1)/Math.log(T1/T2);
    check(`${key} ${alloy} contour reproduces published exponent`,Math.abs(recovered-model.n)<1e-10,
      `n=${fmt(recovered,1)}; table 2 gives ${fmt(model.n,1)}; digitized anchor +/- 10 C`);
  }
}

const blueIron10=temperatureC(THERMAL.blue.iron,10);
const blueIron1m=temperatureC(THERMAL.blue.iron,1e6);
const blueCr10=temperatureC(THERMAL.blue.chromium,10);
const blueCr1m=temperatureC(THERMAL.blue.chromium,1e6);
check('one blue class has multiple thermal histories',blueIron10-blueIron1m>150,
  `electrolytic iron: ${fmt(blueIron10,0)} C at 10 min and ${fmt(blueIron1m,0)} C at 1,000,000 min`);
check('alloy changes the blue contour',blueCr1m-blueIron1m>250,
  `at 1,000,000 min: electrolytic iron ${fmt(blueIron1m,0)} C; 24.4% Cr steel ${fmt(blueCr1m,0)} C`);

const html=fs.readFileSync(HTML_PATH,'utf8');
const md=fs.readFileSync(MD_PATH,'utf8');
const scalar=(name)=>md.match(new RegExp(`^${name}: "([^"]*)"$`,'m'))?.[1]||'';
const pageTitle=html.match(/<title>([^<]+)<\/title>/)?.[1]||'';
const metaDescription=html.match(/<meta name="description" content="([^"]+)/)?.[1]||'';
const ogDescription=html.match(/<meta property="og:description" content="([^"]+)/)?.[1]||'';
const article=JSON.parse(html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)?.[1]||'null');
check('seoTitle matches the search-facing title',scalar('seoTitle')===pageTitle,`${scalar('seoTitle')} == ${pageTitle}`);
check('dek matches meta, Open Graph and JSON-LD',scalar('dek')===metaDescription && scalar('dek')===ogDescription && scalar('dek')===article.description,'one vetted description on every share surface');
check('poetic title matches H1 and JSON-LD headline',html.includes(`<h1>${scalar('title')}</h1>`) && article.headline===scalar('title'),'frontmatter title, H1 and Article headline agree');
const parseJsNumericArray=(source)=>JSON.parse(source.replace(/(^|[\[,])(-?)\./g,(_m,prefix,sign)=>`${prefix}${sign}0.`));
const htmlFujimura=parseJsNumericArray(html.match(/var FUJIMURA=(\[\[.*?\]\]);/)?.[1]||'null');
const htmlSpectral=parseJsNumericArray(html.match(/var SPECTRAL=(\[\[.*?\]\]);/)?.[1]||'null');
check('rendered Fujimura rows match the verifier',JSON.stringify(htmlFujimura)===JSON.stringify(FUJIMURA),'all 19 x,y,Y,thickness rows string-matched from HTML');
check('rendered spectral tables match the verifier',JSON.stringify(htmlSpectral)===JSON.stringify(SPECTRAL),'all 41 observer and illuminant rows string-matched from HTML');
check('rendered thermal constants match the verifier',html.includes('straw:{iron:{n:30,c:68},chromium:{n:23,c:150}},brown:{iron:{n:30.4,c:120},chromium:{n:33.1,c:440}},blue:{iron:{n:31.1,c:164},chromium:{n:34.3,c:500}}'),'six exponents and six graph anchors string-matched from HTML');
const requiredHtml=[
  '<title>Steel Temper Colors: Oxide Thickness, Time and Temperature</title>',
  'https://artwaste.land/strata/the-color-that-was-not-a-temperature/',
  '"datePublished":"2026-08-25"',
  '"dateModified":"2026-08-25"',
  'data-source-points="19"',
  'data-digitization-c="10"',
  'id="poison-check"',
  'id="independent-check"',
  'id="anchor-check"',
  'CIE illuminant C',
  'sRGB clipping'
];
for (const needle of requiredHtml) check(`HTML carries ${needle}`,html.includes(needle),needle);
check('HTML closes all load-bearing tags',/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html),'final inline script, body and html close in order');
check('frontmatter is publishable',md.includes('date: 2026-08-25') && md.includes('seam: "mechanism"') && md.includes('draft: false'),'date, closed-vocabulary seam and draft flag');
check('share surfaces state the non-unique inverse problem',metaDescription.includes('not a unique thermometer reading') && metaDescription.includes('more than one answer'),'meta description denies uniqueness and names multiple answers');
check('page states Fujimura preparation and model scope',html.includes('polished S15C and S45C steel plates') && html.includes('rapid cooling in still air') && html.includes('not a universal morphology model for steel heat tint'),'specimens, coloring conditions and non-universal scope are explicit');
check('page states thickness inference is model-assigned',html.includes('model-assigned thicknesses') && html.includes('not an independent profilometer measurement'),'measured chromaticity is separated from inferred thickness');
check('plain placard separates chromaticity measurement from thickness inference',scalar('plain').includes('19 measured chromaticity points') && scalar('plain').includes('thicknesses were assigned through the model'),'plain-language surface preserves the distinction');

console.log('\nTHE COLOR THAT WAS NOT A TEMPERATURE, RECOMPUTED\n');
console.log(`54 nm under illuminant C -> x=${fmt(pxy.x,4)} y=${fmt(pxy.y,4)} Y=${fmt(primary.Y,4)}`);
console.log(`Fujimura sub-100 nm table -> 19 points, RMS Delta E76 ${fmt(rmsDE,1)}, max ${fmt(maxDE,1)}`);
console.log(`blue iron contour -> ${fmt(blueIron10,0)} C at 10 min; ${fmt(blueIron1m,0)} C at 1,000,000 min`);
console.log(`blue 24.4% Cr contour -> ${fmt(blueCr10,0)} C at 10 min; ${fmt(blueCr1m,0)} C at 1,000,000 min\n`);
for (const c of checks) console.log(`[${c.pass?' OK ':'FAIL'}] ${c.name}\n       ${c.detail}`);
const failed=checks.filter(c=>!c.pass);
console.log(`\n${checks.length-failed.length}/${checks.length} checks pass\n`);
process.exit(failed.length?1:0);
