// verify.mjs — the chemistry behind the stratum
// "The Flower That Reads the Soil Backwards" (/strata/the-flower-that-tests-your-soil/).
//
// The claim the page corrects: the hydrangea is NOT a pH litmus. In Hydrangea
// macrophylla the blue is a fragile three-component complex — delphinidin-3-
// glucoside + Al3+ + a 5-O-acylquinic-acid co-pigment. What sorts the colour is
// the aluminium content of the sepal, not the acid:
//
//     red   0 – 10   µg Al / g fresh sepal
//     purple 10 – 40 µg Al / g fresh sepal
//     blue   > 40    µg Al / g fresh sepal        (Schreiber et al., BioMetals 2011)
//
// Soil pH only GATES aluminium: acid soil frees Al3+ (gibbsite solubility
// log[Al3+] = 8.5 − 3·pH, so Al3+ multiplies ~1000× per pH unit drop; Lindsay
// 1979), neutral/alkaline soil locks it as insoluble hydroxide. Within one plant
// the vacuolar pH of blue cells (4.1) is HIGHER than red cells (3.3) — blue is
// less acidic inside (Yoshida, Plant Cell Physiol 2003).
//
// What this script proves, offline and from scratch:
//   1. The page's colour bands are exactly the published BioMetals thresholds.
//   2. The colour engine's pH→sepal-Al bridge is pinned to those thresholds and
//      the horticultural pH gate: blue ≤ pH 5.5, purple (5.5,6.5], red > 6.5,
//      saturating at a 55 µg/g cap (colour stops bluing past ~40).
//   3. The phosphate lock keeps the flower pink at ANY pH.
//   4. Gibbsite solubility reproduces the displayed 10 / 0.01 / 1e-5 µM values and
//      the exact ×1000-per-pH-unit slope (three protons per aluminium).
//   5. The vacuolar-pH inversion: 4.1 (blue) > 3.3 (red).
//   6. The SHIPPED index.html contains the same constants and figures, so the
//      drawing and the numbers cannot silently disagree.
//
//   run:  node research/the-flower-that-tests-your-soil/verify.mjs
//
// No dependencies. Every number the page displays is recomputed here.

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

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── Sourced constants (must match the shipped inline script) ────────────────
const RED_MAX = 10;   // µg Al / g fresh sepal   (BioMetals 2011)
const BLUE_MIN = 40;  // µg Al / g fresh sepal   (BioMetals 2011)
const AL_CAP = 55;    // model saturation cap (colour stops bluing past ~40)
const PH_BLUE = 5.5;  // horticultural blue onset (Proven Winners) → pinned to 40 µg/g
const PH_PINK = 6.5;  // horticultural pink boundary → pinned to 10 µg/g
const AL_SLOPE = (BLUE_MIN - RED_MAX) / (PH_BLUE - PH_PINK); // = -30 µg/g per pH unit
const LOGK = 8.5;     // gibbsite / soil-Al: log[Al3+] = LOGK − 3·pH (Lindsay 1979)
const P_LOCK_AL = 5;  // phosphate-locked → root-available Al stays in the red band
const VAC_BLUE = 4.1; // vacuolar pH, blue cells (Plant Cell Physiol 2003)
const VAC_RED = 3.3;  // vacuolar pH, red cells

// ── the colour engine, recomputed independently ─────────────────────────────
const clamp = (x, a, b) => (x < a ? a : x > b ? b : x);
const sepalAl = (pH, phosLock) =>
  phosLock ? P_LOCK_AL : clamp(BLUE_MIN + AL_SLOPE * (pH - PH_BLUE), 0, AL_CAP);
const band = (al) => (al < RED_MAX ? 'red' : al < BLUE_MIN ? 'purple' : 'blue');
const alSolubility = (pH) => Math.pow(10, LOGK - 3 * pH); // mol/L

// ── 1. Colour bands equal the published BioMetals thresholds ────────────────
console.log('\n— colour bands vs BioMetals 2011 (µg Al / g fresh sepal) —');
ok('red / purple boundary = 10 µg/g', RED_MAX === 10, `${RED_MAX}`);
ok('purple / blue boundary = 40 µg/g', BLUE_MIN === 40, `${BLUE_MIN}`);
ok('slope of pinned bridge = −30 µg/g per pH unit', approx(AL_SLOPE, -30, 1e-9), `${AL_SLOPE}`);

// ── 2. The pinned pH→sepal-Al bridge lands on the published gate ─────────────
console.log('\n— pH → sepal Al → colour (pinned to thresholds + horticultural gate) —');
const cases = [
  { pH: 4.5, al: 55.0, band: 'blue'   },  // saturated (capped)
  { pH: 5.0, al: 55.0, band: 'blue'   },  // still capped
  { pH: 5.5, al: 40.0, band: 'blue'   },  // blue onset, exactly 40
  { pH: 6.0, al: 25.0, band: 'purple' },
  { pH: 6.5, al: 10.0, band: 'purple' },  // pink boundary, exactly 10
  { pH: 7.0, al:  0.0, band: 'red'    },
  { pH: 8.0, al:  0.0, band: 'red'    },
];
for (const c of cases) {
  const al = sepalAl(c.pH, false);
  const b = band(al);
  ok(`pH ${c.pH.toFixed(1)}  →  ${al.toFixed(1)} µg/g  →  ${b}`,
     approx(al, c.al, 1e-9) && b === c.band, `expected ${c.al.toFixed(1)}/${c.band}`);
}
ok('blue only at pH ≤ 5.5', band(sepalAl(5.5, false)) === 'blue' && band(sepalAl(5.6, false)) === 'purple');
ok('red only at pH > 6.5',  band(sepalAl(6.5, false)) === 'purple' && band(sepalAl(6.6, false)) === 'red');
ok('saturation cap holds (more acid ≠ bluer past cap)',
   sepalAl(4.0, false) === AL_CAP && sepalAl(3.0, false) === AL_CAP, `cap=${AL_CAP}`);
ok('colour is monotone: more acid → more Al',
   [4,5,6,7,8].every((p, i, a) => i === 0 || sepalAl(a[i-1], false) >= sepalAl(p, false)));

// ── 3. Phosphate lock: pink at ANY pH (the honest twist) ────────────────────
console.log('\n— high-phosphate soil locks aluminium: pink at any pH —');
const lockPHs = [4.0, 4.5, 5.0, 5.5];
ok('phosphate-locked Al = 5 µg/g → red band', sepalAl(4.5, true) === P_LOCK_AL && band(P_LOCK_AL) === 'red');
ok('locked flower stays pink even in sour soil (pH 4.0–5.5)',
   lockPHs.every((p) => band(sepalAl(p, true)) === 'red'),
   `all red despite pH ${lockPHs[0]}–${lockPHs[lockPHs.length-1]}`);

// ── 4. Gibbsite solubility: displayed µM values + exact ×1000/pH slope ───────
console.log('\n— gibbsite Al³⁺ solubility  log[Al³⁺] = 8.5 − 3·pH —');
const uM = (pH) => alSolubility(pH) * 1e6; // mol/L → µmol/L
const solCases = [
  { pH: 4.5, uM: 10 },      // 10^(8.5−13.5)=10^-5 M = 10 µM
  { pH: 5.5, uM: 0.01 },    // 10^-8 M = 0.01 µM
  { pH: 6.5, uM: 1e-5 },    // 10^-11 M = 1e-5 µM
];
for (const c of solCases) {
  ok(`pH ${c.pH.toFixed(1)}  →  [Al³⁺] ≈ ${c.uM} µM`, approx(uM(c.pH), c.uM, Math.max(c.uM * 1e-6, 1e-12)),
     `${uM(c.pH).toExponential(2)} µM`);
}
ok('×1000 per pH unit (slope −3 = three H⁺ per Al)',
   [4.5, 5.5, 6.5, 7.0].every((p) => approx(alSolubility(p) / alSolubility(p + 1), 1000, 1e-6)),
   `${(alSolubility(4.5) / alSolubility(5.5)).toFixed(0)}×`);
ok('~million-fold over the pH 6.5→4.5 gate',
   approx(uM(4.5) / uM(6.5), 1e6, 1), `${(uM(4.5) / uM(6.5)).toExponential(1)}`);

// ── 5. The vacuolar-pH inversion (blue is LESS acidic inside) ────────────────
console.log('\n— vacuolar pH within one plant (Plant Cell Physiol 2003) —');
ok('blue cells pH = 4.1', VAC_BLUE === 4.1);
ok('red cells pH = 3.3', VAC_RED === 3.3);
ok('blue cells are LESS acidic inside than red cells', VAC_BLUE > VAC_RED, `Δ=${(VAC_BLUE - VAC_RED).toFixed(1)}`);

// ── 6. The shipped page carries the same constants and figures ──────────────
console.log('\n— parity: shipped index.html contains the same numbers —');
const here = path.dirname(fileURLToPath(import.meta.url));
const pagePath = path.resolve(here, '../../public/strata/the-flower-that-tests-your-soil/index.html');
let html = '';
try {
  html = fs.readFileSync(pagePath, 'utf8');
} catch (e) {
  ok('read shipped index.html', false, String(e && e.message));
}
if (html) {
  const has = (needle) => html.includes(needle);
  // the inline-script constants must equal the verifier's constants
  ok('script defines RED_MAX = 10',   has('RED_MAX = 10'));
  ok('script defines BLUE_MIN = 40',  has('BLUE_MIN = 40'));
  ok('script defines AL_CAP = 55',    has('AL_CAP = 55'));
  ok('script defines PH_BLUE = 5.5',  has('PH_BLUE = 5.5'));
  ok('script defines PH_PINK = 6.5',  has('PH_PINK = 6.5'));
  ok('script defines LOGK = 8.5',     has('LOGK = 8.5'));
  ok('script defines P_LOCK_AL = 5',  has('P_LOCK_AL = 5'));
  // the sourced science, in prose
  ok('names delphinidin-3-glucoside', has('delphinidin-3-glucoside'));
  ok('names the acylquinic-acid co-pigment', has('acylquinic-acid'));
  ok('states the gibbsite slope 8.5 − 3·pH', has('8.5 − 3·pH'));
  ok('states the ×1000-per-pH-unit gate', has('1000&times;'));
  ok('shows vacuolar pH 4.1 (blue)', has('>4.1<'));
  ok('shows vacuolar pH 3.3 (red)', has('>3.3<'));
  ok('cites BioMetals for the bands', has('BioMetals'));
  ok('says the blue structure is still unsolved', has('still unsolved'));
  ok('keeps species precision (macrophylla / serrata change)',
     has('macrophylla') && has('serrata') && has('arborescens') && has('paniculata'));
  ok('honest one-liner: chemistry gates aluminium, aluminium colours',
     has('soil chemistry gates aluminium; aluminium colours the flower'));
  ok('canonical + dated 2026-07-09',
     has('https://artwaste.land/strata/the-flower-that-tests-your-soil/') && has('2026-07-09'));
  ok('load-bearing closing tags present', /<\/script>\s*<\/body>\s*<\/html>/.test(html));
}

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