import { readFileSync } from "node:fs";
import { pathToFileURL } from "node:url";

export function words(text) {
  return text.toLowerCase().normalize("NFKC").replace(/[’‘]/g, "'").replace(/[^a-z0-9\s]/g, "").trim().split(/\s+/).filter(Boolean);
}

export function score(reference, hypothesis) {
  const a = words(reference), b = words(hypothesis);
  const matrix = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
  for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
    matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
  }
  const operations = [];
  let i = a.length, j = b.length;
  while (i || j) {
    if (i && j && matrix[i][j] === matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)) {
      operations.push({ type: a[i - 1] === b[j - 1] ? "equal" : "substitution", reference: a[--i], hypothesis: b[--j] });
    } else if (i && matrix[i][j] === matrix[i - 1][j] + 1) operations.push({ type: "deletion", reference: a[--i], hypothesis: "" });
    else operations.push({ type: "insertion", reference: "", hypothesis: b[--j] });
  }
  const errors = matrix[a.length][b.length];
  return { referenceWords: a.length, hypothesisWords: b.length, errors, werPercent: a.length ? Number((100 * errors / a.length).toFixed(2)) : null, normalization: "NFKC; lowercase; remove punctuation; split on whitespace; no abbreviation expansion", operations: operations.reverse() };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  if (process.argv.length !== 4) throw new Error("Usage: node score-transcript.mjs reference.txt hypothesis.txt");
  console.log(JSON.stringify(score(readFileSync(process.argv[2], "utf8"), readFileSync(process.argv[3], "utf8")), null, 2));
}
