import assert from 'node:assert/strict';
import { readFile, writeFile, mkdtemp, copyFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
import { execFileSync, spawnSync } from 'node:child_process';

const root = fileURLToPath(new URL('.', import.meta.url));
const args = process.argv.slice(2);
if (args.length > 1 || (args.length && (!args[0].startsWith('--checker=') || !args[0].slice('--checker='.length)))) {
  throw new Error('Usage: node verify-checker.mjs [--checker=./checker.mjs]');
}
// Resolve an explicitly downloaded checker from the current directory. The
// default preserves the repository command without requiring public-source
// readers to reproduce the repository's directory layout.
const checkerPath = args.length
  ? resolve(process.cwd(), args[0].slice('--checker='.length))
  : fileURLToPath(new URL('../../public/tools/passage/checker.mjs', import.meta.url));
const source = await readFile(checkerPath, 'utf8');
const { verifyRoute, validateProject, angularDelta, interpolatePose } = await import(pathToFileURL(checkerPath).href);
const cases = [];
let assertions = 0;
function check(condition, message) { assert.ok(condition, message); assertions++; }
function close(actual, expected, tolerance, message) { check(Math.abs(actual - expected) <= tolerance, `${message}: ${actual} versus ${expected}`); }
function project({ size = [10, 10, 10], boxes = [{ center: [0, 0, 0], size: [0.5, 0.5, 0.5] }], obstacles = [], path = [[2, 2, 2, 0, 0, 0], [8, 2, 2, 0, 0, 0]], margin = 0.05 } = {}) {
  return { version: 1, name: 'Independent fixture', world: { size, obstacles }, furniture: { label: 'Test item', boxes }, start: path[0], goal: path[path.length - 1], margin, path };
}
function result(name, model, status) {
  const observed = verifyRoute(model);
  check(observed.status === status, `${name} status: ${observed.status} (${observed.reason})`);
  check(observed.ok === (status === 'verified'), `${name} ok agrees with status`);
  if (observed.ok) check(observed.minClearance > model.margin, `${name} continuous lower bound exceeds margin`);
  cases.push({ name, project: model, expected: status, result: observed });
  return observed;
}

const straight = project();
const straightResult = result('Straight translation: analytic clearance 1.75 m', straight, 'verified');
check(straightResult.minClearance <= 1.75, 'Continuous bound does not exceed the analytic actual minimum');
check(straightResult.segments > 1, 'Long movement actually subdivides');

const offset = project({ boxes: [{ center: [1, 0, 0], size: [0.2, 0.2, 0.2] }], path: [[5, 5, 5, 0, Math.PI / 2, 0]], margin: 0.1 });
const offsetResult = result('Quarter-turn rotates a component offset to z=4', offset, 'verified');
close(offsetResult.minClearance, 3.9 - offsetResult.numericalGuard, 1e-12, 'Analytically derived non-centred quarter-turn clearance');

const obstacle = { id: 'block', label: 'Block', center: [5, 2, 2], size: [0.2, 0.2, 0.2] };
const tunnel = project({ obstacles: [obstacle] });
result('Clear endpoints cross an obstacle halfway', tunnel, 'collision');

const quarter = project({ obstacles: [{ ...obstacle, center: [3, 2, 2] }], path: [[1, 2, 2, 0, 0, 0], [9, 2, 2, 0, 0, 0]] });
const quarterResult = result('Endpoints and midpoint clear, quarter-point collides', quarter, 'collision');
close(quarterResult.details.t, 0.25, 0, 'Subdivision finds quarter-point collision');

const rotation = project({ boxes: [{ center: [0, 0, 0], size: [3, 0.4, 0.4] }], obstacles: [{ id: 'rotation-block', center: [5, 5, 6.35], size: [0.3, 0.3, 0.3] }], path: [[5, 5, 5, 0, 0, 0], [5, 5, 5, 0, Math.PI, 0]] });
result('A long item sweeps into an obstacle between clear rotations', rotation, 'collision');

const rotationQuarter = project({ boxes: [{ center: [1, 0, 0], size: [0.1, 0.1, 0.1] }], obstacles: [{ id: 'quarter-turn-block', center: [5 + Math.SQRT1_2, 5, 5 - Math.SQRT1_2], size: [0.2, 0.2, 0.2] }], path: [[5, 5, 5, 0, 0, 0], [5, 5, 5, 0, Math.PI, 0]] });
result('Rotation endpoints and midpoint clear, quarter-turn collides', rotationQuarter, 'collision');

const asymmetricHalfTurn = project({ size: [4, 2, 4], boxes: [{ center: [1, 0, 0], size: [0.2, 0.2, 0.2] }], obstacles: [{ id: 'wrong-half-turn', center: [2, 1, 3], size: [0.4, 0.4, 0.4] }], path: [[2, 1, 2, 0, 0, 0], [2, 1, 2, 0, Math.PI, 0]], margin: 0.02 });
result('Asymmetric half-turn passes only along the declared positive-pi arc', asymmetricHalfTurn, 'verified');

const tipped = project({ boxes: [{ center: [0, 0, 0], size: [0.8, 2, 0.8] }, { center: [0.5, 0.2, 0], size: [0.3, 0.3, 0.3] }], path: [[2, 3, 3, 0, 0, 0], [7, 3, 6, 0.3, 1.2, 0.6]] });
result('Translation, tipping and turning a multi-box item', tipped, 'verified');

const hollow = project({ boxes: [{ center: [-1, 0, 0], size: [0.5, 2, 2] }, { center: [1, 0, 0], size: [0.5, 2, 2] }], obstacles: [{ id: 'inside-gap', center: [5, 5, 5], size: [1, 1, 1] }], path: [[5, 5, 5, 0, 0, 0]], margin: 0.1 });
const hollowResult = result('An obstacle inside the empty space between furniture boxes', hollow, 'verified');
close(hollowResult.minClearance, 0.25 - hollowResult.numericalGuard, 1e-12, 'Hollow shape analytic gap');

const floor = project({ boxes: [{ center: [0, 0, 0], size: [1, 1, 1] }], path: [[2, 0.4, 2, 0, 0, 0]] });
result('Floor collision', floor, 'collision');
const ceiling = project({ boxes: [{ center: [0, 0, 0], size: [1, 1, 1] }], path: [[2, 9.8, 2, 0, 0, 0]] });
result('Ceiling collision', ceiling, 'collision');
result('Boundary clearance is part of the requested margin', project({ margin: 2, path: [[2, 2, 2, 0, 0, 0]] }), 'inconclusive');
result('Touching the floor cannot certify positive margin', project({ path: [[2, 0.25, 2, 0, 0, 0]], margin: 0.001 }), 'inconclusive');
const diagonalMargin = project({ boxes: [{ center: [0, 0, 0], size: [1, 1, 1] }], obstacles: [{ center: [5.65, 5, 5.65], size: [0.2, 0.2, 0.2] }], path: [[5, 5, 5, 0, 0, 0]], margin: 0.06 });
result('A weak SAT margin bound is not falsely called a collision', diagonalMargin, 'inconclusive');
check(Math.hypot(0.05, 0.05) > diagonalMargin.margin, 'Analytic actual diagonal clearance exceeds the requested margin');

const wrapped = project({ boxes: [{ center: [0, 0, 0], size: [3, 0.4, 0.4] }], obstacles: [{ id: 'would-hit-long-arc', center: [5, 5, 6.35], size: [0.3, 0.3, 0.3] }], path: [[5, 5, 5, 0, 179 * Math.PI / 180, 0], [5, 5, 5, 0, -179 * Math.PI / 180, 0]] });
result('179 to -179 degrees follows the short arc', wrapped, 'verified');
close(angularDelta(179 * Math.PI / 180, -179 * Math.PI / 180), 2 * Math.PI / 180, 1e-14, 'Shortest angular change');
close(angularDelta(0, -Math.PI), Math.PI, 0, 'Half-turn tie is positive');
close(interpolatePose(wrapped.start, wrapped.goal, 0.5)[4], Math.PI, 1e-14, 'Wrapped midpoint is pi');

const extraBox = project({ boxes: [{ center: [0, 0, 0], size: [0.2, 0.2, 0.2] }, { center: [1, 0, 0], size: [0.4, 0.4, 0.4] }], obstacles: [{ center: [6, 5, 5], size: [0.2, 0.2, 0.2] }], path: [[5, 5, 5, 0, 0, 0]] });
result('A collision in the second furniture component is not ignored', extraBox, 'collision');

const shallow = verifyRoute(straight, straight.path, { maxDepth: 0 });
check(shallow.status === 'inconclusive' && !shallow.ok, 'Unproved clear midpoint remains inconclusive at depth zero');
const limited = verifyRoute(straight, straight.path, { maxIntervals: 1 });
check(limited.status === 'inconclusive' && !limited.ok, 'One interval is not silently expanded into an unlimited proof');
for (const options of [{ maxDepth: 25 }, { maxDepth: Infinity }, { maxIntervals: Infinity }, { maxIntervals: -1 }, { maxDepth: 1.5 }, null, []]) {
  check(verifyRoute(straight, straight.path, options).status === 'invalid', 'Malformed/unbounded verification options rejected');
}

const malformed = [
  null,
  { ...straight, version: 2 },
  { ...straight, margin: -1 },
  { ...straight, margin: NaN },
  { ...straight, margin: '0.1' },
  { ...straight, world: { size: [10, 0, 10], obstacles: [] } },
  { ...straight, world: { size: [10, Infinity, 10], obstacles: [] } },
  { ...straight, furniture: { boxes: [] } },
  { ...straight, furniture: { boxes: [{ center: [0, 0, 0], size: [1, -1, 1] }] } },
  { ...straight, furniture: { boxes: [{ center: [0, 0, 0], size: [1, 1e-300, 1] }] } },
  { ...straight, path: [] },
  { ...straight, path: [[2, 2, 2, 0, 0]] },
  { ...straight, path: [[2, 2, 2, 0, 0, NaN]] },
  { ...straight, path: [[3, 2, 2, 0, 0, 0], straight.goal] },
  { ...straight, path: [straight.start, [7, 2, 2, 0, 0, 0]] },
  { ...straight, path: Array(8193).fill(straight.start) },
  { ...straight, world: { ...straight.world, obstacles: Array(513).fill(obstacle) } },
  { ...straight, furniture: { boxes: Array(65).fill(straight.furniture.boxes[0]) } },
];
for (const model of malformed) check(verifyRoute(model).status === 'invalid', 'Malformed route/project refused');
check(validateProject(straight).ok, 'Valid model accepted without normalization');

let seed = 190721;
function random() { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 4294967296; }
for (let i = 0; i < 50; i++) {
  const start = [3 + random(), 3 + random(), 3 + random(), random() * 2, random() * 2, random() * 2];
  const goal = [6 + random(), 3 + random(), 6 + random(), random() * 2, random() * 2, random() * 2];
  const boxes = [{ center: [0, 0, 0], size: [0.3 + random(), 0.3 + random(), 0.3 + random()] }, { center: [0.4, 0.1, -0.1], size: [0.2, 0.3, 0.4] }];
  const model = project({ boxes, path: [start, goal], obstacles: [{ id: 'corner', center: [1, 1, 1], size: [0.5, 0.5, 0.5] }], margin: 0.02 });
  result(`Seeded open-room movement ${i + 1}`, model, 'verified');
}

// Execute the downloaded artifact in an otherwise empty directory. The CLI
// receives serialized values and has no engine, package manifest or repo imports.
const temporary = await mkdtemp(join(tmpdir(), 'passage-checker-'));
await copyFile(checkerPath, join(temporary, 'checker.mjs'));
await writeFile(join(temporary, 'project.json'), JSON.stringify(tipped));
const portable = JSON.parse(execFileSync(process.execPath, ['checker.mjs', 'project.json'], { cwd: temporary, encoding: 'utf8' }));
check(portable.ok && portable.status === 'verified', 'Standalone CLI reproduces the route verdict');
await writeFile(join(temporary, 'forged.json'), JSON.stringify(tunnel));
const forgedCLI = spawnSync(process.execPath, ['checker.mjs', 'forged.json'], { cwd: temporary, encoding: 'utf8' });
check(forgedCLI.status === 1 && JSON.parse(forgedCLI.stdout).status === 'collision', 'Portable checker rejects the forged route');
await writeFile(join(temporary, 'broken.json'), '{');
check(spawnSync(process.execPath, ['checker.mjs', 'broken.json'], { cwd: temporary }).status === 2, 'Malformed JSON uses the separate CLI error exit');

// Meaningful planted defects: each breaks a physical/continuity requirement
// rather than testing that the implementation returns its own written constants.
const faults = [
  ['omit translation displacement', 'Math.hypot(...a.slice(0, 3).map((value, i) => b[i] - value))', '0', quarter, false],
  ['omit rotational displacement', 'radius * a.slice(3).reduce((sum, value, i) => sum + Math.abs(angularDelta(value, b[i + 3])), 0)', '0', rotationQuarter, false],
  ['certify sampled midpoints only', 'const continuousClearance = test.gap - bound;', 'const continuousClearance = test.gap;', quarter, false],
  ['ignore floor and ceiling', 'coordinate < 3', 'coordinate < 0', floor, false],
  ['ignore all obstacles', 'obstacle < project.world.obstacles.length', 'obstacle < 0', tunnel, false],
  ['ignore later furniture components', 'index < project.furniture.boxes.length', 'index < 1', extraBox, false],
  ['overstate certified clearance', 'minimum = Math.min(minimum, continuousClearance);', 'minimum = 1000;', straight, true],
];
const killed = [];
for (let i = 0; i < faults.length; i++) {
  const [name, before, after, model, clearanceFault] = faults[i];
  check(source.includes(before), `Mutation anchor exists: ${name}`);
  const mutantPath = join(temporary, `mutant-${i}.mjs`);
  await writeFile(mutantPath, source.replace(before, after));
  const mutant = await import(pathToFileURL(mutantPath).href);
  const observed = mutant.verifyRoute(model);
  const exposed = clearanceFault ? observed.minClearance > 1.75 : observed.ok;
  // A mutation is killed when our real acceptance assertion would reject its
  // observed result: forbidden route acceptance or an impossible claimed bound.
  check(exposed, `Fixture exposes mutation: ${name}`);
  killed.push(name);
}

await writeFile(join(root, 'checker-cases.json'), JSON.stringify(cases, null, 2) + '\n');
const summary = { checker: 'passage-checker-1.0.0', namedCases: cases.length - 50, seededCases: 50, rejectedMalformedModels: malformed.length, assertions, plantedFaultsExposed: killed, portableCLI: true };
await writeFile(join(root, 'checker-results.json'), JSON.stringify(summary, null, 2) + '\n');
console.log(JSON.stringify(summary, null, 2));
