// verify.mjs — re-derive every operable claim in "The Grey the Edge Invented".
// Run: node research/lightness-edges/verify.mjs   (exits non-zero on any failure)
//
// Nothing here trusts the page. Each check recomputes a number the page shows
// and asserts the relationship the page claims. The honesty bar: where a claim
// is about PERCEPTION (which no array can measure), the check tests the MODEL's
// output and the perceptual direction is cited, never faked.

import {
  cornsweet, mach, simcon, whites,
  dog, reconstruct, borderMean, extent, argExtrema, plateauValue,
} from './engine.mjs';

let pass = 0, fail = 0;
const eps = 1e-9;
function ok(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  — ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  — ' + detail : ''}`); }
}
const near = (a, b, t = 1e-6) => Math.abs(a - b) <= t;

console.log('\nCORNSWEET — identical plateaus, a difference invented at the edge');
{
  const N = 512, L0 = 128, A = 48;
  const cs = cornsweet(N, L0, A);
  const left = plateauValue(cs, 0.10), right = plateauValue(cs, 0.90);
  ok('both plateaus are exactly equal grey', left === right && left === L0, `L(0.10)=${left} == L(0.90)=${right} = ${L0}`);
  ok('the far edges agree too', plateauValue(cs, 0.02) === plateauValue(cs, 0.98), `${plateauValue(cs,0.02)} == ${plateauValue(cs,0.98)}`);
  // the ONLY physical difference is at the border: a light cusp left, dark cusp right
  const justLeft = cs[Math.round((0.5 - 0.5 / N) * (N - 1))];
  const justRight = cs[Math.round((0.5 + 1.5 / N) * (N - 1))];
  ok('left of the border is lighter than right of it', justLeft > justRight, `${justLeft.toFixed(1)} > ${justRight.toFixed(1)}`);
  const ex = extent(cs);
  ok('cusp reaches L0±A and no further', near(ex.hi, L0 + A, 0.5) && near(ex.lo, L0 - A, 0.5), `[${ex.lo.toFixed(1)}, ${ex.hi.toFixed(1)}]`);
}

console.log('\nA BALANCED CENTRE-SURROUND IS BLIND TO ABSOLUTE LEVEL');
{
  for (const c of [0, 64, 128, 200, 255]) {
    const flat = new Float64Array(256).fill(c);
    const r = dog(flat);
    let m = 0; for (const v of r) m = Math.max(m, Math.abs(v));
    ok(`constant field ${c} → response ≈ 0 everywhere`, m < eps, `max|resp| = ${m.toExponential(2)}`);
  }
}

console.log('\nMACH — a straight ramp, yet the filter shows bands the photons lack');
{
  const N = 512, Llo = 70, Lhi = 185, rs = 0.38, re = 0.62;
  const m = mach(N, Llo, Lhi, rs, re);
  // the raw ramp is exactly linear: second difference ~0 inside the ramp
  const i1 = Math.round(0.45 * (N - 1)), i2 = Math.round(0.55 * (N - 1));
  let maxSecond = 0;
  for (let i = i1; i <= i2; i++) maxSecond = Math.max(maxSecond, Math.abs(m[i + 1] - 2 * m[i] + m[i - 1]));
  ok('the raw ramp is exactly linear (no bands in the numbers)', maxSecond < 1e-9, `max|2nd diff| = ${maxSecond.toExponential(2)}`);
  ok('the plateaus are flat', plateauValue(m, 0.1) === Llo && plateauValue(m, 0.9) === Lhi, `${Llo} … ${Lhi}`);
  // the DoG response has a dark band (min) at the foot and a bright band (max) at the knee
  const r = dog(m);
  const { iMin, iMax } = argExtrema(r);
  const xMin = iMin / (N - 1), xMax = iMax / (N - 1);
  ok('dark band sits at the foot of the ramp', Math.abs(xMin - rs) < 0.03, `x_min = ${xMin.toFixed(3)} ≈ rs ${rs}`);
  ok('bright band sits at the knee of the ramp', Math.abs(xMax - re) < 0.03, `x_max = ${xMax.toFixed(3)} ≈ re ${re}`);
  ok('the response is ≈0 on the flat plateaus', Math.abs(r[Math.round(0.15 * (N - 1))]) < 0.5 && Math.abs(r[Math.round(0.85 * (N - 1))]) < 0.5,
     `resp(0.15)=${r[Math.round(0.15*(N-1))].toFixed(3)}, resp(0.85)=${r[Math.round(0.85*(N-1))].toFixed(3)}`);
  // The honest crack in the classic account (Ross, Holt & Johnstone 1984): a
  // single DoG responds even MORE strongly at a sharp STEP — yet no Mach band
  // is seen there. So the edge filter already OVER-predicts.
  const step = mach(N, Llo, Lhi, 0.5, 0.5);         // rs==re → a pure step
  const rStep = dog(step);
  const peakRamp = Math.max(...[...r].map(Math.abs));
  const peakStep = Math.max(...[...rStep].map(Math.abs));
  ok('a single DoG responds even harder at a STEP than at the ramp', peakStep > peakRamp,
     `|resp|_step ${peakStep.toFixed(2)} > |resp|_ramp ${peakRamp.toFixed(2)} — yet no band is seen at a step (model over-predicts)`);
}

console.log('\nCORNSWEET, THROUGH THE MODEL — the ladder\'s middle rung');
{
  const N = 512, L0 = 128, A = 48;
  const cs = cornsweet(N, L0, A);
  const r = dog(cs);
  // a purely LOCAL filter fires only at the edge and is ~0 on BOTH plateaus —
  // so it cannot, by itself, tell the two plateaus apart.
  const rl = r[Math.round(0.15 * (N - 1))], rr = r[Math.round(0.85 * (N - 1))];
  ok('DoG response is ≈0 on both plateaus (edge filter alone is blind here)', Math.abs(rl) < 0.5 && Math.abs(rr) < 0.5,
     `resp(0.15)=${rl.toFixed(3)}, resp(0.85)=${rr.toFixed(3)}`);
  const bip = argExtrema(r);
  ok('and fires bipolar right at the border', Math.abs(bip.iMin - N / 2) < N * 0.06 && Math.abs(bip.iMax - N / 2) < N * 0.06,
     `spike near x=0.5`);
  // integrate the edges, discount slow gradients → a STEP appears between the plateaus
  const rec = reconstruct(cs, 5);
  const dRec = plateauValue(rec, 0.10) - plateauValue(rec, 0.90);
  ok('edge-integration reconstructs a plateau difference ≈ 2A', Math.abs(dRec - 2 * A) < 4, `Δrec = ${dRec.toFixed(1)} (2A = ${2*A})`);
  ok('reconstruction makes the light-cusp side the lighter plateau', plateauValue(rec, 0.10) > plateauValue(rec, 0.90),
     `rec(0.10)=${plateauValue(rec,0.10).toFixed(1)} > rec(0.90)=${plateauValue(rec,0.90).toFixed(1)}`);
  // control: a genuine slow ramp is DISCOUNTED (no sharp edge to keep) — the
  // model then reports no reflectance step, i.e. it reads the ramp as lighting.
  const m = mach(N, 70, 185, 0.3, 0.7);
  const recM = reconstruct(m, 5);
  const dM = Math.abs(plateauValue(recM, 0.9) - plateauValue(recM, 0.1));
  ok('a slow ramp is discounted (reconstruction stays flat)', dM < 2, `Δrec(ramp) = ${dM.toFixed(2)}`);
}

console.log('\nSIMULTANEOUS CONTRAST — the same grey, two surrounds; DoG gets the sign RIGHT');
{
  const N = 512, Lp = 128;
  const s = simcon(N, Lp);
  ok('both test patches are exactly the same grey', plateauValue(s, 0.28) === Lp && plateauValue(s, 0.72) === Lp, `both = ${Lp}`);
  // a COARSER-scale centre-surround (its surround reaches across the small patch
  // into the field) — the scale at which contrast between patch and field lives
  const r = dog(s, 6, 1.6);
  // mean response over each patch
  const mean = (c, half = 0.05) => {
    const i0 = Math.round((c - half) * (N - 1)), i1 = Math.round((c + half) * (N - 1));
    let a = 0; for (let i = i0; i <= i1; i++) a += r[i]; return a / (i1 - i0 + 1);
  };
  const onDark = mean(0.28), onLight = mean(0.72);
  ok('patch on dark → positive response (predicted lighter)', onDark > 0, `⟨resp⟩ = ${onDark.toFixed(3)}`);
  ok('patch on light → negative response (predicted darker)', onLight < 0, `⟨resp⟩ = ${onLight.toFixed(3)}`);
  ok('the model orders them the way people see them', onDark > onLight, `${onDark.toFixed(3)} > ${onLight.toFixed(3)}`);
}

console.log('\nWHITE\'S ILLUSION — the same grey again, but now the local model gets it BACKWARDS');
{
  const { grid, patchA, patchB } = whites();
  // patch A on the black bars, patch B on the white bars — identical grey
  ok('both test patches are exactly the same grey', grid[patchA.y0][patchA.x0] === grid[patchB.y0][patchB.x0],
     `A=${grid[patchA.y0][patchA.x0]} == B=${grid[patchB.y0][patchB.x0]}`);
  const bA = borderMean(grid, patchA), bB = borderMean(grid, patchB);
  // patch A's long left/right borders abut WHITE bars → whiter surround
  ok('patch A (on black bars) has the WHITER surround', bA > bB, `border⟨A⟩=${bA.toFixed(1)} > border⟨B⟩=${bB.toFixed(1)}`);
  // a border-contrast / lateral-inhibition account therefore predicts A DARKER…
  // …but the cited percept (White 1979) is that A looks LIGHTER. The reversal:
  ok('border contrast predicts A darker — OPPOSITE the cited percept (A looks lighter)', bA > bB,
     'checkable pixel fact; the perceptual direction is cited, not measured here');
}

console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'}: ${pass}/${pass + fail} checks`);
process.exit(fail === 0 ? 0 : 1);
