#!/usr/bin/env node
// verify-light-meter.mjs — the light meter cannot lie about itself.
//
// Three families, and the third is the one that matters most:
//
//   1. The engine copied into public/tools/light-meter/ is byte-identical to
//      what PROVENANCE.md says it is. A tool whose provenance file has drifted
//      from the tool is worse than one with no provenance file.
//   2. The exposure mathematics still means what the page says it means.
//   3. Every number the PAGE states about its own accuracy is checked against
//      the bench artifact and the shipped gates. The page claims "0.95 stops",
//      "5%", "1.5 above, 0.5 below"; if the bench is re-run and those move, or
//      if someone edits a gate without re-running the bench, this fails. That
//      is what stops the prose and the instrument drifting apart.
//
//   node verify-light-meter.mjs

import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = dirname(fileURLToPath(import.meta.url));
const TOOL = join(ROOT, 'public/tools/light-meter');

const results = [];
const check = (family, name, fn) => {
  try {
    const detail = fn();
    results.push({ family, name, ok: true, detail: detail ?? '' });
  } catch (error) {
    results.push({ family, name, ok: false, detail: error.message });
  }
};
const eq = (a, b, what) => {
  if (a !== b) throw new Error(`${what}: expected ${b}, got ${a}`);
  return `${what} = ${a}`;
};
const near = (a, b, tol, what) => {
  if (!(Math.abs(a - b) <= tol)) throw new Error(`${what}: ${a} is not within ${tol} of ${b}`);
  return `${what} = ${typeof a === 'number' ? a.toFixed(3) : a}`;
};

const page = readFileSync(join(TOOL, 'index.html'), 'utf8');
const provenance = readFileSync(join(TOOL, 'PROVENANCE.md'), 'utf8');
const bench = JSON.parse(readFileSync(join(ROOT, 'research/light-meter/bench.json'), 'utf8'));

/* --- 1. the copy is the file the checks check --------------------- */

const listed = [...provenance.matchAll(/^([\w/.-]+\.js)\s+([0-9a-f]{64})$/gm)];

check('provenance', 'PROVENANCE.md lists the engine', () =>
  eq(listed.length, 11, 'files listed'));

for (const [, file, want] of listed) {
  check('provenance', `${file} matches its recorded hash`, () => {
    const got = createHash('sha256').update(readFileSync(join(TOOL, file))).digest('hex');
    if (got !== want) throw new Error(`hash drifted\n      recorded ${want}\n      actual   ${got}`);
    return `${file} ${got.slice(0, 12)}…`;
  });
}

check('provenance', 'no relative asset paths, which the short host would break', () => {
  // light.artwaste.land serves this page at "/", so anything loaded relatively
  // resolves against the short host's root and 404s. Found live, after the
  // first deploy served a tool whose entire script tag was missing.
  const relative = [...page.matchAll(/(?:src|href)="(\.\/[^"]*)"/g)].map((m) => m[1]);
  if (relative.length) throw new Error(`relative on a page served from two paths: ${relative.join(', ')}`);
  return 'every asset path is absolute';
});

// Changed 2026-10-29. This used to require a link to github.com/artwasteland/light-meter,
// which made the check enforce a claim that was false for every reader: that repository is
// private and answers 404 from outside. What a reader can actually follow is the provenance
// note, which lists the hash of every engine file the page serves. So the page must link
// that, and must not link a repository a reader cannot open. If the repository is made
// public, restore the old link and its requirement here.
check('provenance', 'the page points the reader at the code it runs', () => {
  if (!page.includes('href="/tools/light-meter/PROVENANCE.md"')) throw new Error('no link to the provenance note that lists the served engine');
  if (page.includes('github.com/artwasteland/light-meter')) throw new Error('links a private repository a reader cannot open');
  return 'links PROVENANCE.md, which lists the served files and their hashes';
});

/* --- 2. the mathematics still means what the page says ------------ */

const { ev100, rebalance, apertureIndexOf, shutterIndexOf, isoIndexOf, targetEv, applyReciprocity } =
  await import(join(TOOL, 'exposure.js'));
const { GATES, evFromCapture, gateCapture, BRIGHTNESS_TO_EV } = await import(join(TOOL, 'calibration.js'));
const { MIDDLE_GREY, analyseFrame } = await import(join(TOOL, 'analysis.js'));

check('maths', 'sunny 16 is EV 15, as the URL grammar promises', () => {
  const indices = { iso: isoIndexOf(100), shutter: shutterIndexOf(1 / 128), aperture: apertureIndexOf(16) };
  return near(ev100(indices), 15, 1e-9, 'EV100 of f/16, 1/125, ISO 100');
});

check('maths', 'the page’s worked link resolves to sunny 16', () => {
  // The page tells the reader that ?ev=15&iso=400&f=16 works out the shutter.
  if (!page.includes('ev=15') || !page.includes('f=16')) throw new Error('the worked URL example is gone from the page');
  const t = (16 * 16) / 2 ** (15 + Math.log2(400 / 100));
  return near(1 / t, 512, 1, 'shutter denominator at ISO 400');
});

check('maths', 'turning one dial moves the other two, and the exposure holds', () => {
  // The page's central promise. Stop the aperture down two stops from
  // ISO 400, 1/125, f/8: the shutter and the ISO must both take a share.
  const r = rebalance({
    indices: { iso: 12, shutter: 42, aperture: 48 },
    ev: 11,
    changed: 'aperture',
    priority: ['shutter', 'aperture', 'iso'],
  });
  if (!(r.absorbed.includes('shutter') && r.absorbed.includes('iso'))) {
    throw new Error(`only ${r.absorbed.join('+')} moved; the spread is broken`);
  }
  return near(ev100(r.indices), 11, 1e-9, 'EV after the spread');
});

check('maths', 'a pinned parameter hands its stranded share back', () => {
  // An adversarial verifier measured a 1.33-stop miss here before the
  // hand-back pass existed: aperture pinned, shutter with headroom, target
  // reachable and missed. Kept as a permanent tripwire.
  const r = rebalance({
    indices: { iso: 12, shutter: 42, aperture: 78 },
    ev: 23,
    locks: { iso: true },
    priority: ['shutter', 'aperture', 'iso'],
  });
  return near(ev100(r.indices), 23, 1e-9, 'EV with the aperture pinned');
});

check('maths', 'a photograph exposed to middle grey reports its own settings', () => {
  const r = evFromCapture({
    exif: { fNumber: 8, exposureTime: 1 / 128, iso: 100 },
    frame: { metered: MIDDLE_GREY, clippedHigh: 0, clippedLow: 0, range: 2 },
  });
  return near(r.ev, 13, 1e-9, 'EV of f/8 at 1/125, ISO 100');
});

check('maths', 'APEX brightness converts as the code claims', () =>
  eq(BRIGHTNESS_TO_EV, 5, 'EV100 = BrightnessValue + this'));

check('maths', 'an 18% grey card meters as 18%', () => {
  const grey = Math.round(255 * (1.055 * 0.18 ** (1 / 2.4) - 0.055));
  const px = new Uint8ClampedArray(16 * 16 * 4);
  for (let i = 0; i < px.length; i += 4) { px[i] = px[i + 1] = px[i + 2] = grey; px[i + 3] = 255; }
  return near(analyseFrame(px, 16, 16).metered, MIDDLE_GREY, 0.002, 'measured luminance of a grey card');
});

check('maths', 'reciprocity lengthens a long exposure and leaves a short one alone', () => {
  if (applyReciprocity(1 / 125, { exponent: 1.31 }).extraStops !== 0) throw new Error('a short exposure was corrected');
  const long = applyReciprocity(8, { exponent: 1.31 });
  if (!(long.seconds > 8)) throw new Error('a long exposure was not lengthened');
  return `8s becomes ${long.seconds.toFixed(1)}s on a 1.31 film`;
});

check('maths', 'more compensation means more light, which is less EV', () =>
  near(targetEv({ meteredEv: 12, compensation: 1 }), 11, 1e-9, 'target EV at +1 stop'));

/* --- 3. the page cannot outrun its own evidence ------------------- */

const worstBox = Math.max(...bench.resampling.map((r) => Math.abs(r.resampledError)));
const worstPoint = Math.max(...bench.resampling.map((r) => Math.abs(r.pointSampledError)));
const clipAt10 = bench.clipping.find((r) => r.targetClip === 0.1);
const preview = bench.exposable.find((c) => c.name.includes('preview'));

/** Every number the page asserts about itself, and where it has to come from. */
const CLAIMS = [
  ['under-reads by up to 0.95 stops', () => near(worstBox, 0.95, 0.01, 'worst box-filtered error')],
  ['worst case 0.12 stops', () => near(worstPoint, 0.12, 0.01, 'worst point-sampled error')],
  ['10% of the frame blown costs 0.10 stops', () => near(Math.abs(clipAt10.error), 0.10, 0.01, 'error at 10% clipped')],
  ['Refuses a reference past 5%', () => eq(GATES.maxClipped, 0.05, 'maxClipped')],
  ['Accepts 1.5 stops above, 0.5 below', () => {
    eq(GATES.maxStopsAboveGrey, 1.5, 'maxStopsAboveGrey');
    return eq(GATES.maxStopsBelowGrey, 0.5, 'maxStopsBelowGrey');
  }],
  ['about EV 0.6 to EV 17', () => {
    near(preview.evLow, 0.6, 0.1, 'lowest exposable EV');
    return near(preview.evHigh, 17.0, 0.1, 'highest exposable EV');
  }],
  ['meter constant of 12.73', () => near(40 / Math.PI, 12.73, 0.01, 'K implied by ISO 12232 SOS')],
  ['0.03 stops from the 12.5', () => near(Math.abs(Math.log2((40 / Math.PI) / 12.5)), 0.03, 0.005, 'stops between K=12.73 and K=12.5')],
];

for (const [phrase, prove] of CLAIMS) {
  check('claims', `the page says "${phrase}"`, () => {
    if (!page.includes(phrase)) throw new Error(`the page no longer contains this claim, so the check below is stale`);
    return prove();
  });
}

check('claims', 'the asymmetric window really is asymmetric', () => {
  if (!(GATES.maxStopsBelowGrey < GATES.maxStopsAboveGrey)) throw new Error('below is not the tighter side');
  const dark = gateCapture({ exif: { fNumber: 8, exposureTime: 0.01, iso: 100 },
    frame: { metered: MIDDLE_GREY / 2, clippedHigh: 0, clippedLow: 0, range: 2 } });
  if (dark.ok) throw new Error('a reference a stop below middle grey was accepted');
  return 'a stop under is refused, a stop over is not';
});

check('claims', 'the page states what it cannot do', () => {
  for (const must of ['Incident metering', 'Flash metering', 'no dome']) {
    if (!page.includes(must)) throw new Error(`the page no longer states: ${must}`);
  }
  return 'incident, flash and the reason for both';
});

/* --- report ------------------------------------------------------- */

let family = '';
for (const r of results) {
  if (r.family !== family) { family = r.family; console.log(`\n${family.toUpperCase()}`); }
  console.log(`  ${r.ok ? 'ok  ' : 'FAIL'}  ${r.name}${r.detail ? `\n          ${r.detail}` : ''}`);
}

const failed = results.filter((r) => !r.ok).length;
console.log(`\n${results.length - failed}/${results.length} checks passed\n`);
process.exit(failed ? 1 : 0);
