import fs from 'node:fs';

const htmlPath = new URL('../../public/strata/bhargava-290/index.html', import.meta.url);
const html = fs.readFileSync(htmlPath, 'utf8');

const CRITICAL_290 = [
  1, 2, 3, 5, 6, 7, 10, 13, 14, 15, 17, 19, 21, 22, 23,
  26, 29, 30, 31, 34, 35, 37, 42, 58, 93, 110, 145, 203, 290
];
const CRITICAL_15 = [1, 2, 3, 5, 6, 7, 10, 14, 15];

function fail(message) {
  throw new Error(message);
}

function assert(condition, message) {
  if (!condition) fail(message);
}

function sameArray(actual, expected, label) {
  assert(actual.length === expected.length, `${label}: length ${actual.length}, expected ${expected.length}`);
  actual.forEach((value, index) => {
    assert(value === expected[index], `${label}: entry ${index} is ${value}, expected ${expected[index]}`);
  });
}

function extractBrowserArray(name) {
  const match = html.match(new RegExp(`var ${name} = \\[([^\\]]+)\\]`));
  assert(match, `could not find browser array ${name}`);
  return match[1].split(',').map((part) => Number(part.trim()));
}

function determinant(matrix) {
  const n = matrix.length;
  if (n === 0) return 1n;
  if (n === 1) return BigInt(matrix[0][0]);
  let total = 0n;
  for (let column = 0; column < n; column += 1) {
    const minor = matrix.slice(1).map((row) => row.filter((_, index) => index !== column));
    const term = BigInt(matrix[0][column]) * determinant(minor);
    total += column % 2 === 0 ? term : -term;
  }
  return total;
}

function integerSqrt(value) {
  assert(value >= 0n, 'integer square root received a negative value');
  if (value < 2n) return value;
  let x = 1n << BigInt(Math.ceil(value.toString(2).length / 2));
  while (true) {
    const next = (x + value / x) >> 1n;
    if (next >= x) return x;
    x = next;
  }
}

function doubledGram(form) {
  const rank = form.diag.length;
  const matrix = Array.from({ length: rank }, (_, row) =>
    Array.from({ length: rank }, (_, column) => row === column ? 2 * form.diag[row] : 0)
  );
  for (const [row, column, coefficient] of form.cross) {
    matrix[row][column] = coefficient;
    matrix[column][row] = coefficient;
  }
  return matrix;
}

function evaluate(form, vector) {
  let value = 0;
  for (let index = 0; index < form.diag.length; index += 1) {
    value += form.diag[index] * vector[index] * vector[index];
  }
  for (const [row, column, coefficient] of form.cross) {
    value += coefficient * vector[row] * vector[column];
  }
  return value;
}

function assertPositiveDefinite(form) {
  const matrix = doubledGram(form);
  for (let size = 1; size <= matrix.length; size += 1) {
    const leading = matrix.slice(0, size).map((row) => row.slice(0, size));
    assert(determinant(leading) > 0n, `${form.name}: nonpositive leading principal minor ${size}`);
  }
}

function enumerate(form, limit = 290) {
  assertPositiveDefinite(form);
  const matrix = doubledGram(form);
  const fullDeterminant = determinant(matrix);
  const bounds = matrix.map((_, coordinate) => {
    const minor = matrix
      .filter((_, row) => row !== coordinate)
      .map((row) => row.filter((_, column) => column !== coordinate));
    const cofactor = determinant(minor);
    const squaredBound = (BigInt(2 * limit) * cofactor) / fullDeterminant;
    return Number(integerSqrt(squaredBound));
  });
  const witnesses = Array(limit + 1).fill(null);
  const vector = Array(form.diag.length).fill(0);
  let vectorsVisited = 0;

  function walk(coordinate) {
    if (coordinate === vector.length) {
      vectorsVisited += 1;
      const value = evaluate(form, vector);
      if (value >= 0 && value <= limit && witnesses[value] === null) {
        witnesses[value] = vector.slice();
      }
      return;
    }
    for (let value = -bounds[coordinate]; value <= bounds[coordinate]; value += 1) {
      vector[coordinate] = value;
      walk(coordinate + 1);
    }
  }

  walk(0);
  for (let value = 0; value <= limit; value += 1) {
    const witness = witnesses[value];
    if (witness) {
      assert(evaluate(form, witness) === value, `${form.name}: bad witness for ${value}`);
    }
  }
  return { witnesses, bounds, vectorsVisited };
}

function firstTruant(result) {
  for (let value = 1; value < result.witnesses.length; value += 1) {
    if (result.witnesses[value] === null) return value;
  }
  return null;
}

const forms = {
  square: { name: 'x^2', diag: [1], cross: [] },
  squareTwo: { name: 'x^2 + 2y^2', diag: [1, 2], cross: [] },
  B: { name: 'B', diag: [1, 2, 5], cross: [[0, 2, 1], [1, 2, 3]] },
  L145: { name: 'B + 29u^2', diag: [1, 2, 5, 29], cross: [[0, 2, 1], [1, 2, 3]] },
  L290: { name: 'B + 29u^2 + 145v^2', diag: [1, 2, 5, 29, 145], cross: [[0, 2, 1], [1, 2, 3]] },
  universal: { name: 'B + 29u^2 + 145v^2 + 290w^2', diag: [1, 2, 5, 29, 145, 290], cross: [[0, 2, 1], [1, 2, 3]] },
  fourSquares: { name: 'four squares', diag: [1, 1, 1, 1], cross: [] },
  missingSeven: { name: '[1,1,1,9]', diag: [1, 1, 1, 9], cross: [] }
};

sameArray(extractBrowserArray('CRITICAL_290'), CRITICAL_290, 'browser 290 list against primary-source anchor');
sameArray(extractBrowserArray('CRITICAL_15'), CRITICAL_15, 'browser 15 list against primary-source anchor');
assert(html.includes('291') && html.includes('581'), 'browser does not display both isolate coefficients');

const fourSquares = enumerate(forms.fourSquares);
assert(CRITICAL_290.every((value) => fourSquares.witnesses[value]), 'four squares does not hit all 29 targets');
assert(CRITICAL_15.every((value) => fourSquares.witnesses[value]), 'four squares does not hit all nine targets');

const missingSeven = enumerate(forms.missingSeven);
assert(firstTruant(missingSeven) === 7, 'published [1,1,1,9] anchor does not have truant 7');
assert(CRITICAL_15.filter((value) => missingSeven.witnesses[value]).length === 8, '[1,1,1,9] should hit 8 of 9 targets');

const branchNames = ['square', 'squareTwo', 'B', 'L145', 'L290'];
const branchResults = branchNames.map((name) => enumerate(forms[name]));
const truants = [1, ...branchResults.map(firstTruant)];
sameArray(truants, [1, 2, 5, 29, 145, 290], 'escalation truants');

const publishedForm = {
  name: 'published ternary basis',
  diag: [1, 2, 4],
  cross: [[0, 2, -1], [1, 2, -1]]
};
const basisMap = (vector) => [vector[0] + vector[2], vector[1] + vector[2], vector[2]];
for (let x = -5; x <= 5; x += 1) {
  for (let y = -5; y <= 5; y += 1) {
    for (let z = -5; z <= 5; z += 1) {
      const vector = [x, y, z];
      assert(
        evaluate(forms.B, vector) === evaluate(publishedForm, basisMap(vector)),
        `basis change failed at ${vector.join(',')}`
      );
    }
  }
}
assert(determinant([[1, 0, 1], [0, 1, 1], [0, 0, 1]]) === 1n, 'basis change is not unimodular');

const universal = enumerate(forms.universal);
const universalCount = CRITICAL_290.filter((value) => universal.witnesses[value]).length;
assert(universalCount === 29, `universal ending hits ${universalCount} of 29 targets`);

const L290 = branchResults[4];
assert(L290.witnesses.slice(1, 290).every(Boolean), 'L290 must represent 1 through 289');
assert(L290.witnesses[290] === null, 'L290 must miss 290');
for (let remainder = 0; remainder < 290; remainder += 1) {
  assert(L290.witnesses[remainder], `isolate construction lacks base witness for remainder ${remainder}`);
}
for (let quotient = 1; quotient <= 1000; quotient += 1) {
  const n = 291 * quotient + 290;
  assert(n === 291 * (quotient - 1) + 581, `residue-290 identity failed at quotient ${quotient}`);
}
assert(291 === 290 + 1, '291 is not t+1 for t=290');
assert(581 === 2 * 290 + 1, '581 is not 2t+1 for t=290');

console.log(`Published 290 anchor: ${CRITICAL_290.join(', ')}`);
console.log(`Published 15 anchor: ${CRITICAL_15.join(', ')}`);
console.log(`Published [1,1,1,9] truant: ${firstTruant(missingSeven)} (${CRITICAL_15.filter((n) => missingSeven.witnesses[n]).length}/9 targets)`);
console.log(`Escalation truants: ${truants.join(' -> ')}`);
console.log(`Universal ending: ${universalCount}/29 critical values represented`);
console.log('Isolate ending: 291 = 290+1 and 581 = 2*290+1; both residue cases checked');
console.log('Scope: this verifier does not reprove the 290 theorem or reproduce its full escalator and modular-form computation.');
