import { readFileSync } from 'node:fs';

let checks = 0;

function assert(condition, message) {
  if (!condition) throw new Error(`FAIL: ${message}`);
  checks += 1;
}

function key([x, y, z]) {
  return `${x},${y},${z}`;
}

function invariant([x, y, z]) {
  return x * x + 4 * y * z;
}

function same(a, b) {
  return a.length === b.length && a.every((value, index) => value === b[index]);
}

function isPrime(n) {
  if (!Number.isSafeInteger(n) || n < 2) return false;
  if (n % 2 === 0) return n === 2;
  for (let d = 3; d * d <= n; d += 2) {
    if (n % d === 0) return false;
  }
  return true;
}

function inTheoremDomain(n) {
  return isPrime(n) && n % 4 === 1;
}

// Independent enumerator. The browser factors (p - x^2) / 4 by its divisors.
// This verifier instead searches all positive x, y, z in explicit bounds.
function enumerateWindmills(n) {
  const triples = [];
  const bound = Math.floor((n - 1) / 4);
  for (let x = 1; x * x < n; x += 1) {
    for (let y = 1; y <= bound; y += 1) {
      for (let z = 1; z <= bound; z += 1) {
        if (x * x + 4 * y * z === n) triples.push([x, y, z]);
      }
    }
  }
  return triples;
}

function flip([x, y, z]) {
  return [x, z, y];
}

function zagier([x, y, z]) {
  if (x < y - z) return [x + 2 * z, z, y - z - x];
  if (y - z < x && x < 2 * y) return [2 * y - x, y, x + z - y];
  if (x > 2 * y) return [x - 2 * y, x + z - y, y];
  return null;
}

function bruteTwoSquares(n) {
  const found = [];
  for (let a = 1; a * a < n; a += 1) {
    for (let b = a; a * a + b * b <= n; b += 1) {
      if (a * a + b * b === n) found.push([a, b]);
    }
  }
  return found;
}

function runOrbit(n, map = zagier, order = 'flip-then-zagier') {
  if (!inTheoremDomain(n)) throw new Error(`outside theorem domain: ${n}`);
  const triples = enumerateWindmills(n);
  let current = [1, 1, (n - 1) / 4];
  const steps = [];
  while (current[1] !== current[2]) {
    if (steps.length > triples.length) throw new Error(`orbit failed to terminate for ${n}`);
    let next;
    if (order === 'flip-then-zagier') {
      const turned = flip(current);
      next = map(turned);
      steps.push({ before: current, flip: turned, after: next });
    } else {
      const turned = map(current);
      next = turned && flip(turned);
      steps.push({ before: current, zagier: turned, after: next });
    }
    if (!next) throw new Error(`undefined orbit branch for ${n}`);
    current = next;
  }
  return { triples, steps, final: current, squares: [current[0], current[1] + current[2]] };
}

function verifyPrime(n) {
  const triples = enumerateWindmills(n);
  const members = new Set(triples.map(key));
  assert(triples.length > 0, `S_${n} is nonempty`);
  assert(triples.every(t => t.every(v => Number.isInteger(v) && v > 0)), `S_${n} is positive`);
  assert(triples.every(t => invariant(t) === n), `S_${n} satisfies the invariant`);

  const zImages = triples.map(zagier);
  assert(zImages.every(Boolean), `Z has no boundary case on S_${n}`);
  assert(zImages.every(t => members.has(key(t))), `Z closes on S_${n}`);
  assert(triples.every((t, i) => invariant(zImages[i]) === invariant(t)), `Z preserves ${n}`);
  assert(triples.every(t => same(zagier(zagier(t)), t)), `Z squared is identity on S_${n}`);

  const zFixed = triples.filter(t => same(zagier(t), t));
  const seed = [1, 1, (n - 1) / 4];
  assert(zFixed.length === 1 && same(zFixed[0], seed), `Z has sole fixed point ${key(seed)}`);
  assert(triples.length % 2 === 1, `S_${n} has odd cardinality`);

  assert(triples.every(t => members.has(key(flip(t)))), `flip closes on S_${n}`);
  assert(triples.every(t => same(flip(flip(t)), t)), `flip squared is identity on S_${n}`);
  const flipFixed = triples.filter(t => same(flip(t), t));
  assert(flipFixed.length % 2 === 1 && flipFixed.length > 0, `flip has an odd nonzero fixed set on S_${n}`);

  const orbit = runOrbit(n);
  assert(orbit.final[1] === orbit.final[2], `orbit reaches a flip fixed point for ${n}`);
  assert(orbit.steps.length <= triples.length, `orbit for ${n} stays within its finite census`);
  const [a, b] = orbit.squares;
  assert(a * a + b * b === n, `orbit produces ${n} = ${a}^2 + ${b}^2`);

  const independent = bruteTwoSquares(n).map(pair => pair.slice().sort((u, v) => u - v));
  const obtained = [a, b].sort((u, v) => u - v);
  assert(independent.length === 1, `independent search finds one positive unordered pair for ${n}`);
  assert(same(independent[0], obtained), `orbit agrees with independent square search for ${n}`);
  return { triples, zFixed, flipFixed, orbit };
}

function makeMutant(options) {
  return function mutant([x, y, z]) {
    let branch = -1;
    let out = null;
    if (options.firstLe ? x <= y - z : x < y - z) {
      branch = 0;
      out = [x + 2 * z, z, y - z - x];
    } else {
      const lower = options.lowerLe ? y - z <= x : y - z < x;
      const upper = options.upperLe ? x <= 2 * y : x < 2 * y;
      if (lower && upper) {
        branch = 1;
        out = [2 * y - x, y, x + z - y];
      } else if (options.thirdGe ? x >= 2 * y : x > 2 * y) {
        branch = 2;
        out = [x - 2 * y, x + z - y, y];
      }
    }
    if (out && options.bumpBranch === branch) out[options.bumpCoordinate] += 1;
    return out;
  };
}

function enginePasses(map) {
  const boundaryA = [1, 3, 2];
  const boundaryB = [2, 1, 1];
  if (map(boundaryA) !== null || map(boundaryB) !== null) return false;
  for (const n of [5, 13, 17, 29, 37, 41]) {
    const triples = enumerateWindmills(n);
    const members = new Set(triples.map(key));
    for (const t of triples) {
      const image = map(t);
      if (!image || !members.has(key(image)) || invariant(image) !== n) return false;
      const back = map(image);
      if (!back || !same(back, t)) return false;
    }
  }
  return true;
}

function main() {
  const publishedS29 = ['1,1,7', '1,7,1', '3,1,5', '3,5,1', '5,1,1'];
  const publishedOrbit29 = ['3,1,5', '5,1,1'];
  const computedS29 = enumerateWindmills(29).map(key).sort();

  assert(JSON.stringify(computedS29) === JSON.stringify(publishedS29), 'external anchor: Chan Table 2, all five triples of S_29');
  const result29 = verifyPrime(29);
  assert(JSON.stringify(result29.orbit.steps.map(s => key(s.after))) === JSON.stringify(publishedOrbit29), 'external anchor: Chan Figure 7, two combined steps');
  assert(result29.orbit.steps.length === 2, 'default orbit has exactly 2 flip-then-Zagier steps');
  assert(same(result29.orbit.final, [5, 1, 1]), 'default flip fixed point is (5,1,1)');
  assert(5 * 5 + 2 * 2 === 29, 'default identity is 29 = 5^2 + 2^2');

  const qualifying = [];
  for (let n = 5; n <= 997; n += 4) {
    if (isPrime(n)) qualifying.push(n);
  }
  for (const n of qualifying) verifyPrime(n);

  assert(zagier([1, 3, 2]) === null, 'negative control: x = y-z is reported undefined');
  assert(zagier([2, 1, 1]) === null, 'negative control: x = 2y is reported undefined');
  assert(!inTheoremDomain(25) && !inTheoremDomain(65), 'negative control: congruent composites are outside the theorem');
  let compositeRejection = '';
  try {
    runOrbit(25);
  } catch (error) {
    compositeRejection = error.message;
  }
  assert(compositeRejection === 'outside theorem domain: 25', 'algorithm refuses the composite 25 at the prime guard');

  assert(enginePasses(zagier), 'unmutated engine passes the independent harness');
  const inequalityMutants = [
    ['x < y-z changed to x <= y-z', { firstLe: true }],
    ['y-z < x changed to y-z <= x', { lowerLe: true }],
    ['x < 2y changed to x <= 2y', { upperLe: true }],
    ['x > 2y changed to x >= 2y', { thirdGe: true }]
  ];
  for (const [name, options] of inequalityMutants) {
    assert(!enginePasses(makeMutant(options)), `mutation rejected: ${name}`);
  }
  for (let branch = 0; branch < 3; branch += 1) {
    for (let coordinate = 0; coordinate < 3; coordinate += 1) {
      const mutant = makeMutant({ bumpBranch: branch, bumpCoordinate: coordinate });
      assert(!enginePasses(mutant), `mutation rejected: branch ${branch + 1}, output ${coordinate + 1}`);
    }
  }

  const wrongOrder = runOrbit(29, zagier, 'zagier-then-flip');
  assert(wrongOrder.steps.length !== 2, 'wrong composition order disagrees with the published two-step anchor');

  const page = readFileSync(new URL('../../public/strata/zagier-involution/index.html', import.meta.url), 'utf8');
  assert(page.includes('data-default-census="5"'), 'page default census is bound to the recomputed anchor');
  assert(page.includes('data-default-orbit-steps="2"'), 'page default orbit length is bound to the recomputed anchor');
  assert(page.includes('data-default-identity="29=5^2+2^2"'), 'page default identity is bound to the recomputed anchor');

  console.log(`External anchor S_29: ${computedS29.length} triples`);
  console.log(`Z fixed points for 29: ${result29.zFixed.map(key).join(' ')}`);
  console.log(`Flip fixed points for 29: ${result29.flipFixed.map(key).join(' ')}`);
  console.log(`Published orbit anchor: ${result29.orbit.steps.length} steps`);
  console.log('Final identity: 29 = 5^2 + 2^2');
  console.log(`Qualifying primes checked through 997: ${qualifying.length}`);
  console.log(`Inequality and arithmetic mutants rejected: ${inequalityMutants.length + 9}`);
  console.log(`PASS: ${checks} exact assertions`);
}

try {
  main();
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
