#!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const htmlPath = path.resolve(here, "../../public/strata/quasicrystal-diffraction/index.html");

let checks = 0;

function ok(condition, message) {
  if (!condition) throw new Error(message);
  checks += 1;
}

function near(actual, expected, tolerance, label) {
  ok(Math.abs(actual - expected) <= tolerance,
    `${label}: expected ${expected}, got ${actual}`);
}

function dot(a, b) {
  return a.reduce((sum, value, index) => sum + value * b[index], 0);
}

function norm(a) {
  return Math.sqrt(dot(a, a));
}

function mul(matrix, vector) {
  return matrix.map((row) => dot(row, vector));
}

function determinant(source) {
  const a = source.map((row) => row.slice());
  let det = 1;
  for (let column = 0; column < a.length; column += 1) {
    let pivot = column;
    for (let row = column + 1; row < a.length; row += 1) {
      if (Math.abs(a[row][column]) > Math.abs(a[pivot][column])) pivot = row;
    }
    if (Math.abs(a[pivot][column]) < 1e-14) return 0;
    if (pivot !== column) {
      [a[pivot], a[column]] = [a[column], a[pivot]];
      det *= -1;
    }
    const divisor = a[column][column];
    det *= divisor;
    for (let row = column + 1; row < a.length; row += 1) {
      const factor = a[row][column] / divisor;
      for (let k = column + 1; k < a.length; k += 1) {
        a[row][k] -= factor * a[column][k];
      }
    }
  }
  return det;
}

const phi = (1 + Math.sqrt(5)) / 2;
const conjugate = -1 / phi;
const physicalScale = Math.sqrt(4 + 2 * phi);
const internalScale = Math.sqrt(2 + 2 * conjugate * conjugate);

const physical = [
  [1, -1, 0, 0, phi, phi],
  [phi, phi, 1, -1, 0, 0],
  [0, 0, phi, phi, 1, -1]
].map((row) => row.map((value) => value / physicalScale));

const internal = [
  [1, -1, 0, 0, conjugate, conjugate],
  [conjugate, conjugate, 1, -1, 0, 0],
  [0, 0, conjugate, conjugate, 1, -1]
].map((row) => row.map((value) => value / internalScale));

for (let i = 0; i < 3; i += 1) {
  near(dot(physical[i], physical[i]), 1, 1e-12, `physical row ${i} norm`);
  near(dot(internal[i], internal[i]), 1, 1e-12, `internal row ${i} norm`);
  for (let j = 0; j < 3; j += 1) {
    near(dot(physical[i], internal[j]), 0, 1e-12,
      `physical row ${i} perpendicular to internal row ${j}`);
  }
}

const projectionDeterminant = Math.abs(determinant([...physical, ...internal]));
near(projectionDeterminant, 1, 1e-12, "six-coordinate projection determinant");

const fivefoldTrace = 2 * Math.cos(2 * Math.PI / 5);
near(fivefoldTrace, phi - 1, 1e-14, "fivefold lattice trace");
near(fivefoldTrace * fivefoldTrace + fivefoldTrace - 1, 0, 1e-14,
  "fivefold trace polynomial");

const allowedOrders = [];
for (let n = 1; n <= 12; n += 1) {
  const trace = 2 * Math.cos(2 * Math.PI / n);
  if (Math.abs(trace - Math.round(trace)) < 1e-12) allowedOrders.push(n);
}
ok(allowedOrders.join(",") === "1,2,3,4,6",
  `crystallographic restriction failed: ${allowedOrders.join(",")}`);

function reconstructedSpots() {
  const spots = [{ x: 0, y: 0, ring: 0 }];
  for (const [ring, radius] of [46, 74, 120].entries()) {
    for (let k = 0; k < 10; k += 1) {
      const angle = (k * 36 + (ring % 2 ? 18 : 0)) * Math.PI / 180;
      spots.push({ x: radius * Math.cos(angle), y: radius * Math.sin(angle), ring: ring + 1 });
    }
  }
  return spots;
}

function rotationalResidual(spots, degrees) {
  const angle = degrees * Math.PI / 180;
  const c = Math.cos(angle);
  const s = Math.sin(angle);
  const noncentral = spots.filter((spot) => Math.hypot(spot.x, spot.y) > 1e-9);
  let sumSquares = 0;
  for (const spot of noncentral) {
    const x = c * spot.x - s * spot.y;
    const y = s * spot.x + c * spot.y;
    let best = Infinity;
    for (const candidate of noncentral) {
      best = Math.min(best, Math.hypot(x - candidate.x, y - candidate.y));
    }
    sumSquares += best * best;
  }
  return Math.sqrt(sumSquares / noncentral.length);
}

const spots = reconstructedSpots();
ok(spots.length === 31, `reconstruction point count: ${spots.length}`);
near(rotationalResidual(spots, 36), 0, 1e-10, "nonzero one-tenth-turn residual");
ok(rotationalResidual(spots, 18) > 20, "half-step must not align the reconstruction");
const defaultRotationResidual = rotationalResidual(spots, 18);

function enumerateSites(bound, windowRadius, offset, physicalRadius) {
  const sites = [];
  const index = [0, 0, 0, 0, 0, 0];
  function visit(axis) {
    if (axis < 6) {
      for (let value = -bound; value <= bound; value += 1) {
        index[axis] = value;
        visit(axis + 1);
      }
      return;
    }
    const perpendicular = mul(internal, index);
    perpendicular[0] += offset;
    if (norm(perpendicular) > windowRadius + 1e-12) return;
    const point = mul(physical, index);
    if (norm(point) <= physicalRadius + 1e-12) {
      sites.push({ point, index: index.slice() });
    }
  }
  visit(0);
  return sites;
}

const defaultSites = enumerateSites(2, 0.8, 0, 2.5);
ok(defaultSites.length === 93, `default cut-and-project site count: ${defaultSites.length}`);
ok(defaultSites.some((site) => site.index.every((value) => value === 0)),
  "origin missing from cut-and-project set");

const viewNormal = physical.map((row) => row[0]);
const viewNormalLength = norm(viewNormal);
for (let i = 0; i < 3; i += 1) viewNormal[i] /= viewNormalLength;
let viewU = [-viewNormal[1], viewNormal[0], 0];
const viewULength = norm(viewU);
viewU = viewU.map((value) => value / viewULength);
const viewV = [
  viewNormal[1] * viewU[2] - viewNormal[2] * viewU[1],
  viewNormal[2] * viewU[0] - viewNormal[0] * viewU[2],
  viewNormal[0] * viewU[1] - viewNormal[1] * viewU[0]
];

function screen(point) {
  return [dot(point, viewU), dot(point, viewV)];
}

function directIntensity(sites, q) {
  let real = 0;
  let imaginary = 0;
  for (const site of sites) {
    const phase = 2 * Math.PI * dot(q, site.point);
    real += Math.cos(phase);
    imaginary += Math.sin(phase);
  }
  return (real * real + imaginary * imaginary) / sites.length;
}

near(directIntensity(defaultSites, [0, 0, 0]), defaultSites.length, 1e-10,
  "central direct Fourier intensity");

function modulePeaks(maxL1) {
  const peaks = [];
  const index = [0, 0, 0, 0, 0, 0];
  function visit(axis) {
    if (axis < 6) {
      for (let value = -maxL1; value <= maxL1; value += 1) {
        index[axis] = value;
        visit(axis + 1);
      }
      return;
    }
    const l1 = index.reduce((sum, value) => sum + Math.abs(value), 0);
    if (l1 === 0 || l1 > maxL1) return;
    const q = mul(physical, index);
    peaks.push({ index: index.slice(), q, xy: screen(q), intensity: directIntensity(defaultSites, q) });
  }
  visit(0);
  return peaks;
}

const peaks = modulePeaks(2);
ok(peaks.length === 84, `six-index candidate peak count: ${peaks.length}`);
const strongest = peaks.reduce((best, peak) => peak.intensity > best.intensity ? peak : best);

function reciprocalGrid(sites, size, qMax) {
  const values = [];
  let strongestNoncentral = 0;
  for (let y = 0; y < size; y += 1) {
    for (let x = 0; x < size; x += 1) {
      const qx = -qMax + 2 * qMax * x / (size - 1);
      const qy = -qMax + 2 * qMax * y / (size - 1);
      const q = [
        viewU[0] * qx + viewV[0] * qy,
        viewU[1] * qx + viewV[1] * qy,
        viewU[2] * qx + viewV[2] * qy
      ];
      const value = directIntensity(sites, q);
      values.push(value);
      if (x !== (size - 1) / 2 || y !== (size - 1) / 2) {
        strongestNoncentral = Math.max(strongestNoncentral, value);
      }
    }
  }
  return { values, strongestNoncentral };
}

const grid = reciprocalGrid(defaultSites, 45, 3.2);
ok(grid.values.length === 2025, `reciprocal grid sample count: ${grid.values.length}`);
ok(grid.strongestNoncentral > 1, "reciprocal grid did not recover a noncentral peak");

function bravaisFit(modulePeakList, coefficientLimit, tolerance) {
  const generators = [0, 2, 4].map((column) =>
    screen(physical.map((row) => row[column])));
  let sumSquares = 0;
  let unmatched = 0;
  for (const peak of modulePeakList) {
    let best = Infinity;
    for (let a = -coefficientLimit; a <= coefficientLimit; a += 1) {
      for (let b = -coefficientLimit; b <= coefficientLimit; b += 1) {
        for (let c = -coefficientLimit; c <= coefficientLimit; c += 1) {
          const x = a * generators[0][0] + b * generators[1][0] + c * generators[2][0];
          const y = a * generators[0][1] + b * generators[1][1] + c * generators[2][1];
          best = Math.min(best, Math.hypot(peak.xy[0] - x, peak.xy[1] - y));
        }
      }
    }
    sumSquares += best * best;
    if (best > tolerance) unmatched += 1;
  }
  return { rms: Math.sqrt(sumSquares / modulePeakList.length), unmatched };
}

const fit = bravaisFit(peaks, 2, 0.08);

function bestTranslation(sites, physicalRadius) {
  const points = sites.map((site) => site.point);
  const key = (point) => point.map((value) => Math.round(value * 1e7)).join(",");
  const pointKeys = new Set(points.map(key));
  const origin = points.reduce((best, point) => norm(point) < norm(best) ? point : best);
  const candidates = points
    .map((point) => point.map((value, i) => value - origin[i]))
    .filter((shift) => norm(shift) > 0.2 && norm(shift) < 1.8);
  let best = { matched: 0, tested: 0, fraction: 0, length: 0 };
  for (const shift of candidates) {
    let matched = 0;
    let tested = 0;
    for (const point of points) {
      if (norm(point) > physicalRadius - norm(shift) - 1e-9) continue;
      tested += 1;
      const moved = point.map((value, i) => value + shift[i]);
      if (pointKeys.has(key(moved))) matched += 1;
    }
    const fraction = tested ? matched / tested : 0;
    if (tested >= 7 && fraction > best.fraction) {
      best = { matched, tested, fraction, length: norm(shift) };
    }
  }
  return best;
}

const translation = bestTranslation(defaultSites, 2.5);
ok(translation.tested >= 7, "translation search tested too few interior sites");
ok(translation.fraction < 1, "finite model patch unexpectedly has a perfect searched translation");

console.log("Quasicrystal diffraction verification");
console.log("published anchors checked as source metadata:");
console.log("  8 April 1982; sample 1725; Al-14-at.%-Mn");
console.log("  12 November 1984; Pauling model 26.7 angstroms, about 1,120 atoms, 20 domains");
console.log("  1991 terms published 1992; Nobel announcement 5 October 2011");
console.log(`external anchor, published indexing count: ${physical[0].length} integer indices`);
console.log(`combined projection determinant: ${projectionDeterminant.toFixed(12)}`);
console.log(`fivefold trace 2 cos(72 deg): ${fivefoldTrace.toFixed(12)}`);
console.log(`allowed periodic rotation orders through 12: ${allowedOrders.join(", ")}`);
console.log(`idealized spot reconstruction: ${spots.length} points`);
console.log(`default 18 degree rotational RMS: ${defaultRotationResidual.toFixed(6)} model units`);
console.log(`36 degree rotational RMS: ${rotationalResidual(spots, 36).toExponential(3)} model units`);
console.log(`default cut-and-project sites: ${defaultSites.length}`);
console.log(`central DFT intensity I(0): ${directIntensity(defaultSites, [0, 0, 0]).toFixed(6)}`);
console.log(`six-index candidate peaks: ${peaks.length}`);
console.log(`strongest noncentral candidate I: ${strongest.intensity.toFixed(6)}`);
console.log(`reciprocal grid samples: ${grid.values.length}`);
console.log(`strongest noncentral grid I: ${grid.strongestNoncentral.toFixed(6)}`);
console.log(`three-generator screen fit RMS: ${fit.rms.toFixed(6)}`);
console.log(`three-generator unmatched at 0.08: ${fit.unmatched}/${peaks.length}`);
console.log(`best searched translation: ${translation.matched}/${translation.tested} = ${(100 * translation.fraction).toFixed(2)}%`);

if (fs.existsSync(htmlPath)) {
  const html = fs.readFileSync(htmlPath, "utf8");
  const required = [
    `data-default-sites="${defaultSites.length}"`,
    `data-default-peaks="${peaks.length}"`,
    `data-default-grid="${grid.values.length}"`,
    `data-default-grid-peak="${grid.strongestNoncentral.toFixed(3)}"`,
    `data-default-unmatched="${fit.unmatched}"`,
    `data-default-fit-rms="${fit.rms.toFixed(4)}"`,
    `data-default-translation="${(100 * translation.fraction).toFixed(1)}"`,
    `data-default-rotation-rms="${defaultRotationResidual.toFixed(2)}"`,
    `data-fivefold-trace="${fivefoldTrace.toFixed(6)}"`
  ];
  for (const token of required) ok(html.includes(token), `HTML drift: missing ${token}`);
  const sourceAnchors = [
    "8 April 1982",
    "sample 1725",
    "Al-14-at.%-Mn",
    "12 November 1984",
    "26.7 angstroms",
    "1,120 atoms",
    "20 directed twin domains",
    "1991 terms, report published 1992",
    "5 October 2011",
    "Physical Review Letters 53, 1951, 1984",
    "Journal of Materials Research 1, 13 to 26, 1986",
    "Nature 317, 512 to 514, 1985",
    "Journal of Materials Research 2, 294 to 297, 1987",
    "Nature 326, 372 to 373, 1987",
    "Physical Review Letters 58, 2304 to 2307, 1987",
    "Acta Crystallographica A48, 922 to 946, 1992"
  ];
  for (const anchor of sourceAnchors) {
    ok(html.includes(anchor), `published source anchor missing from HTML: ${anchor}`);
  }
}

console.log(`PASS: ${checks} independent checks`);
