/**
 * Passage portable route checker, format 1.
 * Independent of the path search and rendering code. All distances are metres.
 * A result certifies the supplied rigid-box model, not an actual building or item.
 * See research/passage/continuous-check.md for the derivation and numerical limits.
 */
export const CHECKER_VERSION = 'passage-checker-1.0.0';

const TAU = Math.PI * 2;
const LIMIT = 10000;
const MAX_POSES = 8192;
const MAX_OBSTACLES = 512;
const MAX_BOXES = 64;
const DEFAULT_DEPTH = 20;
const DEFAULT_INTERVALS = 100000;

function invalid(reason, details) {
  return { ok: false, status: 'invalid', minClearance: null, segments: 0, reason, details, checkerVersion: CHECKER_VERSION };
}

function vector(value, length, label, positive = false) {
  if (!Array.isArray(value) || value.length !== length) throw new Error(`${label} must contain exactly ${length} numbers.`);
  for (const n of value) {
    if (typeof n !== 'number' || !Number.isFinite(n) || Math.abs(n) > LIMIT || (positive && n < 1e-5)) {
      throw new Error(`${label} must contain finite ${positive ? 'positive ' : ''}numbers no larger than ${LIMIT}.`);
    }
  }
}

function box(value, label) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be a box object.`);
  vector(value.center, 3, `${label}.center`);
  vector(value.size, 3, `${label}.size`, true);
}

/** Validates the format without mutating or silently repairing it. */
export function validateProject(project) {
  try {
    if (!project || typeof project !== 'object' || Array.isArray(project) || project.version !== 1) throw new Error('Expected a Passage project with version 1.');
    if (!project.world || typeof project.world !== 'object') throw new Error('A world is required.');
    vector(project.world.size, 3, 'world.size', true);
    if (!Array.isArray(project.world.obstacles) || project.world.obstacles.length > MAX_OBSTACLES) throw new Error(`world.obstacles must be an array of at most ${MAX_OBSTACLES} boxes.`);
    project.world.obstacles.forEach((value, i) => box(value, `world.obstacles[${i}]`));
    if (!project.furniture || !Array.isArray(project.furniture.boxes) || project.furniture.boxes.length < 1 || project.furniture.boxes.length > MAX_BOXES) throw new Error(`furniture.boxes must contain 1 to ${MAX_BOXES} rigid boxes.`);
    project.furniture.boxes.forEach((value, i) => box(value, `furniture.boxes[${i}]`));
    vector(project.start, 6, 'start');
    vector(project.goal, 6, 'goal');
    if (typeof project.margin !== 'number' || !Number.isFinite(project.margin) || project.margin < 0 || project.margin > LIMIT) throw new Error('margin must be a finite non-negative distance in metres.');
    return { ok: true };
  } catch (error) {
    return { ok: false, reason: error.message };
  }
}

/** Signed shortest angular change, with +pi selected at the half-turn tie. */
export function angularDelta(a, b) {
  const d = ((b - a) % TAU + TAU) % TAU;
  return d > Math.PI ? d - TAU : d;
}

export function interpolatePose(a, b, t) {
  return a.map((value, i) => value + (i < 3 ? b[i] - value : angularDelta(value, b[i])) * t);
}

const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const WORLD_AXES = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];

// Columns of Ry(ry) Rx(rx) Rz(rz); equivalent to Three.js Euler order YXZ.
function axes(pose) {
  const sx = Math.sin(pose[3]), cx = Math.cos(pose[3]);
  const sy = Math.sin(pose[4]), cy = Math.cos(pose[4]);
  const sz = Math.sin(pose[5]), cz = Math.cos(pose[5]);
  return [
    [cy * cz + sy * sx * sz, cx * sz, -sy * cz + cy * sx * sz],
    [-cy * sz + sy * sx * cz, cx * cz, sy * sz + cy * sx * cz],
    [sy * cx, -sx, cy * cx],
  ];
}

function positioned(localBox, pose, basis) {
  return {
    center: [0, 1, 2].map(i => pose[i] + basis[0][i] * localBox.center[0] + basis[1][i] * localBox.center[1] + basis[2][i] * localBox.center[2]),
    half: localBox.size.map(n => n / 2),
    basis,
  };
}

// Any normalized separating direction provides a LOWER bound on Euclidean
// distance, including when it is not the direction of the closest points.
function separation(moving, fixed) {
  const difference = fixed.center.map((value, i) => value - moving.center[i]);
  const halfFixed = fixed.size.map(n => n / 2);
  const candidates = [...WORLD_AXES, ...moving.basis];
  for (const a of moving.basis) for (const b of WORLD_AXES) {
    const c = cross(a, b), length = Math.hypot(...c);
    // Discarding an unstable direction can only weaken a lower bound.
    if (length > 1e-6) candidates.push(c.map(n => n / length));
  }
  let gap = -Infinity;
  for (const candidate of candidates) {
    const length = Math.hypot(...candidate);
    const direction = candidate.map(n => n / length);
    const movingExtent = moving.half.reduce((sum, h, i) => sum + h * Math.abs(dot(moving.basis[i], direction)), 0);
    const fixedExtent = halfFixed.reduce((sum, h, i) => sum + h * Math.abs(direction[i]), 0);
    gap = Math.max(gap, Math.abs(dot(difference, direction)) - movingExtent - fixedExtent);
  }
  return gap;
}

function shapeRadius(boxes) {
  return Math.max(...boxes.map(value => Math.hypot(...value.center.map((n, i) => Math.abs(n) + value.size[i] / 2))));
}

function clearanceAt(project, pose, numericalGuard) {
  const basis = axes(pose);
  let minimum = Infinity, limiting = null;
  for (let index = 0; index < project.furniture.boxes.length; index++) {
    const moving = positioned(project.furniture.boxes[index], pose, basis);
    for (let coordinate = 0; coordinate < 3; coordinate++) {
      const extent = moving.half.reduce((sum, half, i) => sum + half * Math.abs(basis[i][coordinate]), 0);
      const sides = [moving.center[coordinate] - extent, project.world.size[coordinate] - moving.center[coordinate] - extent];
      for (let side = 0; side < 2; side++) if (sides[side] < minimum) {
        minimum = sides[side];
        limiting = { furnitureBox: index, boundary: ['left', 'floor', 'front', 'right', 'ceiling', 'back'][coordinate + side * 3] };
      }
    }
    for (let obstacle = 0; obstacle < project.world.obstacles.length; obstacle++) {
      const gap = separation(moving, project.world.obstacles[obstacle]);
      if (gap < minimum) {
        minimum = gap;
        limiting = { furnitureBox: index, obstacle, obstacleId: project.world.obstacles[obstacle].id ?? null };
      }
    }
  }
  return { gap: minimum - numericalGuard, rawGap: minimum, limiting };
}

function samePose(a, b, scale) {
  return a.every((value, i) => Math.abs(i < 3 ? b[i] - value : angularDelta(value, b[i])) <= (i < 3 ? 1e-9 * scale : 1e-9));
}

/**
 * Check the declared start-to-goal route with adaptive continuous enclosures.
 * maxDepth and maxIntervals are bounded work budgets, never claims of accuracy.
 * minClearance on success is a conservative certified lower bound over the WHOLE
 * route. A search/verification budget exhaustion yields inconclusive, never ok.
 */
export function verifyRoute(project, path = project?.path, options = {}) {
  const validation = validateProject(project);
  if (!validation.ok) return invalid(validation.reason);
  if (!options || typeof options !== 'object' || Array.isArray(options)) return invalid('Verification options must be an object.');
  const maxDepth = options.maxDepth ?? DEFAULT_DEPTH;
  const maxIntervals = options.maxIntervals ?? DEFAULT_INTERVALS;
  if (!Number.isInteger(maxDepth) || maxDepth < 0 || maxDepth > 24 || !Number.isInteger(maxIntervals) || maxIntervals < 1 || maxIntervals > 200000) return invalid('Verification budgets must be integers: maxDepth 0–24, maxIntervals 1–200000.');
  if (!Array.isArray(path) || path.length < 1 || path.length > MAX_POSES) return invalid(`A route must contain 1 to ${MAX_POSES} poses.`);
  try { path.forEach((pose, i) => vector(pose, 6, `path[${i}]`)); } catch (error) { return invalid(error.message); }
  // Bound total geometry work as well as subdivision count. Hostile projects
  // cannot multiply a large shape, obstacle set and path into an unbounded job.
  const poseWork = project.furniture.boxes.length * (project.world.obstacles.length + 6);
  const geometryBudget = 2000000;
  if (path.length * poseWork > geometryBudget) return invalid('The route and model exceed the geometry work budget.');
  const intervalBudget = Math.min(maxIntervals, Math.floor(geometryBudget / poseWork) - path.length);
  const radius = shapeRadius(project.furniture.boxes);
  const scale = Math.max(1, radius, ...project.world.size, ...project.world.obstacles.flatMap(value => [...value.center.map(Math.abs), ...value.size]), ...path.flatMap(value => value.slice(0, 3).map(Math.abs)));
  const numericalGuard = scale * 1e-8;
  if (!samePose(project.start, path[0], scale) || !samePose(project.goal, path[path.length - 1], scale)) return invalid('The route must begin at the declared start and end at the declared goal.');
  let visits = 0, segments = 0, minimum = Infinity;
  const base = () => ({ minClearance: Number.isFinite(minimum) ? minimum : null, segments, checkedIntervals: visits, checkerVersion: CHECKER_VERSION, numericalGuard });
  for (let i = 0; i < path.length; i++) {
    const test = clearanceAt(project, path[i], numericalGuard);
    if (!(test.gap > project.margin)) {
      const status = test.rawGap < -numericalGuard ? 'collision' : 'inconclusive';
      return { ok: false, status, ...base(), minClearance: test.gap, reason: status === 'collision' ? `Pose ${i + 1} overlaps a boundary or obstacle in the numerical model.` : `Pose ${i + 1} does not provide a conservative bound above the requested clearance.`, details: { poseIndex: i, pose: [...path[i]], ...test } };
    }
  }
  if (path.length === 1) {
    minimum = clearanceAt(project, path[0], numericalGuard).gap;
    return { ok: true, status: 'verified', ...base(), reason: 'The stationary pose has the requested clearance.' };
  }
  for (let edge = 0; edge < path.length - 1; edge++) {
    const a = path[edge], b = path[edge + 1];
    const movement = Math.hypot(...a.slice(0, 3).map((value, i) => b[i] - value)) + radius * a.slice(3).reduce((sum, value, i) => sum + Math.abs(angularDelta(value, b[i + 3])), 0);
    const pending = [{ low: 0, high: 1, depth: 0 }];
    while (pending.length) {
      if (visits >= intervalBudget) return { ok: false, status: 'inconclusive', ...base(), minClearance: null, reason: 'The continuous proof reached its interval or geometry budget.', details: { edge } };
      const interval = pending.pop();
      visits++;
      const t = (interval.low + interval.high) / 2;
      const midpoint = interpolatePose(a, b, t);
      const test = clearanceAt(project, midpoint, numericalGuard);
      if (!(test.gap > project.margin)) {
        const status = test.rawGap < -numericalGuard ? 'collision' : 'inconclusive';
        return { ok: false, status, ...base(), minClearance: test.gap, reason: status === 'collision' ? `Movement ${edge + 1} has an overlapping intermediate pose in the numerical model.` : `Movement ${edge + 1} has an intermediate pose whose requested clearance cannot be certified.`, details: { edge, t, pose: midpoint, ...test } };
      }
      const bound = movement * (interval.high - interval.low) / 2;
      const continuousClearance = test.gap - bound;
      if (continuousClearance > project.margin) {
        segments++;
        minimum = Math.min(minimum, continuousClearance);
      } else if (interval.depth >= maxDepth) {
        return { ok: false, status: 'inconclusive', ...base(), minClearance: null, reason: 'The continuous proof reached its subdivision depth near a tight clearance.', details: { edge, from: interval.low, to: interval.high, depth: interval.depth } };
      } else {
        pending.push({ low: t, high: interval.high, depth: interval.depth + 1 }, { low: interval.low, high: t, depth: interval.depth + 1 });
      }
    }
  }
  return { ok: true, status: 'verified', ...base(), reason: 'Every interval has a continuous clearance bound above the requested margin.' };
}

// The same downloaded file is both an importable browser module and a Node CLI.
// No package, rendering library, network call or path-search implementation is needed.
if (typeof process !== 'undefined' && process.versions?.node && process.argv[1]) {
  const { pathToFileURL } = await import('node:url');
  if (import.meta.url === pathToFileURL(process.argv[1]).href) {
    const file = process.argv[2];
    if (!file) {
      process.stderr.write('Usage: node checker.mjs passage-project.json\n');
      process.exitCode = 2;
    } else {
      try {
        const { readFile, stat } = await import('node:fs/promises');
        if ((await stat(file)).size > 10 * 1024 * 1024) throw new Error('Project JSON exceeds the 10 MB input limit.');
        const project = JSON.parse(await readFile(file, 'utf8'));
        const result = verifyRoute(project);
        process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
        process.exitCode = result.ok ? 0 : 1;
      } catch (error) {
        process.stderr.write(`${error.message}\n`);
        process.exitCode = 2;
      }
    }
  }
}
