// mutate.mjs: does verify.mjs notice a broken engine?
// Run: node research/invisible-exactly-in-focus/mutate.mjs
//
// Each mutation is a plausible slip in public/strata/invisible-exactly-in-focus/engine.mjs. It is
// applied to a copy in a temporary directory, verify.mjs is pointed at the copy (ENGINE=...), and
// the mutation counts as caught only if the verifier then fails.
import { readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';

const HERE = dirname(fileURLToPath(import.meta.url));
const SRC = join(HERE, '../../public/strata/invisible-exactly-in-focus/engine.mjs');
const base = readFileSync(SRC, 'utf8');

const mutations = [
  ['plate shifts the wrong way (exp(+i theta))', 'const pr = a * Math.cos(-th), pi = a * Math.sin(-th);', 'const pr = a * Math.cos(th), pi = a * Math.sin(th);'],
  ['plate dims energy, not amplitude (a^2 used as amplitude)', 'const a = plate ? plate.a : 1,', 'const a = plate ? plate.a * plate.a : 1,'],
  ['defocus uses the paraxial parabola', 'const w = 2 * Math.PI * z * (Math.sqrt(1 / (lambda * lambda) - f2) - 1 / lambda);', 'const w = -Math.PI * lambda * z * f2;'],
  ['defocus sign flipped', 'const w = 2 * Math.PI * z * (Math.sqrt(1 / (lambda * lambda) - f2) - 1 / lambda);', 'const w = -2 * Math.PI * z * (Math.sqrt(1 / (lambda * lambda) - f2) - 1 / lambda);'],
  ['specimen phase taken as advance, not delay', 're[k] = a * Math.cos(sp.phi[k]); im[k] = a * Math.sin(sp.phi[k]);', 're[k] = a * Math.cos(sp.phi[k]); im[k] = -a * Math.sin(sp.phi[k]);'],
  ['intensity taken as (re + im)^2 instead of re^2 + im^2', 'for (let k = 0; k < N * N; k++) I[k] += re[k] * re[k] + im[k] * im[k];', 'for (let k = 0; k < N * N; k++) I[k] += (re[k] + im[k]) ** 2;'],
  ['aperture edge off by a bin', 'if (u * u + v * v > NA * NA * (1 + 1e-12)) continue;\n    let re = 1', 'if (u * u + v * v > NA * NA * 1.05) continue;\n    let re = 1'],
  ['plate ring covers only its inner half', "return r >= pl.r - pl.w - 1e-9 && r <= pl.r + pl.w + 1e-9;", "return r >= pl.r - pl.w - 1e-9 && r <= pl.r + 1e-9;"],
  ['cells drawn with twice the index difference', 'dn = 0.017, dnRod', 'dn = 0.034, dnRod'],
  ['ring of light loses its symmetry (plain rounding)', 'const rs = (x) => Math.sign(x) * Math.round(Math.abs(x));', 'const rs = (x) => Math.round(x + 0.3);'],
];

const dir = mkdtempSync(join(tmpdir(), 'iief-mut-'));
let caught = 0;
const out = [];
for (const [name, from, to] of mutations) {
  if (!base.includes(from)) { out.push(`ERROR  ${name}: pattern not found in engine`); continue; }
  const file = join(dir, `engine-${caught + out.length}.mjs`);
  writeFileSync(file, base.replace(from, to));
  const r = spawnSync(process.execPath, [join(HERE, 'verify.mjs')], { env: { ...process.env, ENGINE: file }, encoding: 'utf8' });
  const fails = (r.stdout.match(/^FAIL/gm) || []).length;
  const ok = r.status !== 0;
  if (ok) caught++;
  out.push(`${ok ? 'CAUGHT' : 'MISSED'}  ${name}${ok ? `  (${fails} check${fails === 1 ? '' : 's'} failed)` : ''}`);
}
rmSync(dir, { recursive: true, force: true });
console.log(['mutate.mjs: /strata/invisible-exactly-in-focus/', ...out, '', `${caught} of ${mutations.length} caught`].join('\n'));
process.exit(caught === mutations.length ? 0 : 1);
