import fs from 'node:fs';

const PAGE = new URL('../../public/strata/cap-set-polynomial/index.html', import.meta.url);
let checks = 0;

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

function mod3(value) {
  const r = value % 3;
  return r < 0 ? r + 3 : r;
}

function key(vector) {
  return vector.join('');
}

function vectors(n) {
  const out = [];
  const total = 3 ** n;
  for (let value = 0; value < total; value += 1) {
    let q = value;
    const vector = Array(n).fill(0);
    for (let i = n - 1; i >= 0; i -= 1) {
      vector[i] = q % 3;
      q = Math.floor(q / 3);
    }
    out.push(vector);
  }
  return out;
}

function completes(x, y) {
  return x.map((xi, i) => mod3(-xi - y[i]));
}

function directZeroTest(x, y, z) {
  for (let i = 0; i < x.length; i += 1) {
    if (mod3(x[i] + y[i] + z[i]) !== 0) return 0;
  }
  return 1;
}

function productPolynomial(x, y, z) {
  let product = 1;
  for (let i = 0; i < x.length; i += 1) {
    const sum = mod3(x[i] + y[i] + z[i]);
    product = mod3(product * mod3(1 - sum * sum));
  }
  return product;
}

function presetCap(n) {
  if (n === 1) return [[0], [1]];
  if (n === 2) return [[0, 0], [0, 1], [1, 0], [1, 1]];
  if (n === 3) {
    const out = [];
    for (let a = 0; a < 3; a += 1) {
      for (let b = 0; b < 3; b += 1) {
        out.push([a, b, mod3(a * a + b * b)]);
      }
    }
    return out;
  }
  if (n === 4) {
    const out = [];
    for (let mask = 0; mask < 16; mask += 1) {
      out.push([
        (mask >> 3) & 1,
        (mask >> 2) & 1,
        (mask >> 1) & 1,
        mask & 1
      ]);
    }
    return out;
  }
  throw new Error(`No preset cap for n=${n}`);
}

function supportCounts(pointList) {
  const members = new Set(pointList.map(key));
  let diagonal = 0;
  let offDiagonal = 0;
  for (const x of pointList) {
    for (const y of pointList) {
      const z = completes(x, y);
      if (!members.has(key(z))) continue;
      if (key(x) === key(y)) diagonal += 1;
      else offDiagonal += 1;
    }
  }
  return { diagonal, offDiagonal };
}

function coefficientRow(n) {
  let row = [1n];
  for (let i = 0; i < n; i += 1) {
    const next = Array(row.length + 2).fill(0n);
    for (let j = 0; j < row.length; j += 1) {
      next[j] += row[j];
      next[j + 1] += row[j];
      next[j + 2] += row[j];
    }
    row = next;
  }
  return row;
}

function monomialCountDP(n, cutoff = Math.floor(2 * n / 3)) {
  return coefficientRow(n)
    .slice(0, cutoff + 1)
    .reduce((sum, value) => sum + value, 0n);
}

function monomialCountEnumeration(n, cutoff = Math.floor(2 * n / 3)) {
  const total = 3 ** n;
  let count = 0n;
  for (let value = 0; value < total; value += 1) {
    let q = value;
    let degree = 0;
    for (let i = 0; i < n; i += 1) {
      degree += q % 3;
      q = Math.floor(q / 3);
    }
    if (degree <= cutoff) count += 1n;
  }
  return count;
}

const LOCAL_TERMS = [
  { coefficient: 1, x: 0, y: 0, z: 0 },
  { coefficient: 2, x: 2, y: 0, z: 0 },
  { coefficient: 2, x: 0, y: 2, z: 0 },
  { coefficient: 2, x: 0, y: 0, z: 2 },
  { coefficient: 1, x: 1, y: 1, z: 0 },
  { coefficient: 1, x: 1, y: 0, z: 1 },
  { coefficient: 1, x: 0, y: 1, z: 1 }
];

function expandedTerms(n) {
  let terms = [{ coefficient: 1, x: [], y: [], z: [] }];
  for (let coordinate = 0; coordinate < n; coordinate += 1) {
    const next = [];
    for (const prior of terms) {
      for (const local of LOCAL_TERMS) {
        next.push({
          coefficient: mod3(prior.coefficient * local.coefficient),
          x: prior.x.concat(local.x),
          y: prior.y.concat(local.y),
          z: prior.z.concat(local.z)
        });
      }
    }
    terms = next;
  }
  return terms;
}

function monomialValue(point, exponents) {
  let value = 1;
  for (let i = 0; i < point.length; i += 1) {
    let factor = 1;
    for (let power = 0; power < exponents[i]; power += 1) {
      factor = mod3(factor * point[i]);
    }
    value = mod3(value * factor);
  }
  return value;
}

function evaluateTerms(terms, x, y, z) {
  let sum = 0;
  for (const term of terms) {
    const value = mod3(
      term.coefficient *
      monomialValue(x, term.x) *
      monomialValue(y, term.y) *
      monomialValue(z, term.z)
    );
    sum = mod3(sum + value);
  }
  return sum;
}

function groupSlices(terms, n) {
  const cutoff = Math.floor(2 * n / 3);
  const groups = { x: [], y: [], z: [] };
  const keys = { x: new Set(), y: new Set(), z: new Set() };
  for (const term of terms) {
    const dx = term.x.reduce((a, b) => a + b, 0);
    const dy = term.y.reduce((a, b) => a + b, 0);
    const dz = term.z.reduce((a, b) => a + b, 0);
    let block = null;
    if (dx <= cutoff) block = 'x';
    else if (dy <= cutoff) block = 'y';
    else if (dz <= cutoff) block = 'z';
    assert(block !== null, `No low-degree block for expanded term at n=${n}`);
    groups[block].push(term);
    keys[block].add(key(term[block]));
  }
  return { groups, keys };
}

function defaultSliceAnchor(n) {
  const terms = expandedTerms(n);
  const grouped = groupSlices(terms, n);
  return [
    ['x', 'y', 'z'].map((block) => grouped.groups[block].length).join(','),
    ['x', 'y', 'z'].map((block) => grouped.keys[block].size).join(',')
  ].join(';');
}

function f(t) {
  return (1 + t + t * t) / (t ** (2 / 3));
}

function goldenMinimum(left, right) {
  const ratio = (Math.sqrt(5) - 1) / 2;
  let a = left;
  let b = right;
  let c = b - ratio * (b - a);
  let d = a + ratio * (b - a);
  for (let i = 0; i < 200; i += 1) {
    if (f(c) < f(d)) {
      b = d;
      d = c;
      c = b - ratio * (b - a);
    } else {
      a = c;
      c = d;
      d = a + ratio * (b - a);
    }
  }
  return (a + b) / 2;
}

function maximumCapBySubset(n) {
  const ambient = vectors(n);
  let best = 0;
  const subsetCount = 2 ** ambient.length;
  for (let mask = 0; mask < subsetCount; mask += 1) {
    const size = mask.toString(2).replaceAll('0', '').length;
    if (size <= best) continue;
    const subset = [];
    for (let i = 0; i < ambient.length; i += 1) {
      if ((mask & (1 << i)) !== 0) subset.push(ambient[i]);
    }
    if (supportCounts(subset).offDiagonal === 0) best = size;
  }
  return best;
}

function attribute(html, name) {
  const match = html.match(new RegExp(`${name}="([^"]+)"`));
  if (!match) throw new Error(`Missing page attribute ${name}`);
  return match[1];
}

function textById(html, id) {
  const pattern = new RegExp(`<[^>]+id="${id}"[^>]*>([\\s\\S]*?)<\\/[^>]+>`);
  const match = html.match(pattern);
  if (!match) throw new Error(`Missing page element #${id}`);
  return match[1].replace(/<[^>]*>/g, '').trim();
}

try {
  console.log('Cap-set polynomial verifier');

  for (let n = 1; n <= 4; n += 1) {
    const ambient = vectors(n);
    let mismatches = 0;
    let triples = 0;
    for (const x of ambient) {
      for (const y of ambient) {
        for (const z of ambient) {
          triples += 1;
          if (productPolynomial(x, y, z) !== directZeroTest(x, y, z)) mismatches += 1;
        }
      }
    }
    assert(mismatches === 0, `Polynomial mismatch in dimension ${n}`);
    console.log(`n=${n}: ${triples.toLocaleString('en-US')} ambient triples, ${mismatches} mismatches`);
  }

  for (let n = 1; n <= 4; n += 1) {
    const cap = presetCap(n);
    const support = supportCounts(cap);
    assert(support.diagonal === cap.length, `Wrong diagonal support for n=${n}`);
    assert(support.offDiagonal === 0, `Preset is not a cap for n=${n}`);
    console.log(`n=${n}: preset size ${cap.length}, tensor support ${support.diagonal} diagonal and ${support.offDiagonal} off diagonal`);
  }

  {
    const cap = presetCap(3);
    const z = completes(cap[0], cap[1]);
    assert(!new Set(cap.map(key)).has(key(z)), 'Chosen completion was already in the cap');
    const enlarged = cap.concat([z]);
    const support = supportCounts(enlarged);
    assert(support.offDiagonal >= 6, 'Inserted line did not create off-diagonal entries');
    assert(support.offDiagonal % 6 === 0, 'Off-diagonal entries do not group into unordered lines');
    assert(directZeroTest(cap[0], cap[1], z) === 1, 'Inserted witness does not sum to zero');
    console.log(`inserted point: ${key(cap[0])} + ${key(cap[1])} + ${key(z)} = 0, off-diagonal support ${support.offDiagonal}`);
  }

  for (let n = 1; n <= 3; n += 1) {
    const terms = expandedTerms(n);
    assert(terms.length === 7 ** n, `Wrong expansion size for n=${n}`);
    const grouped = groupSlices(terms, n);
    const m = monomialCountDP(n);
    for (const block of ['x', 'y', 'z']) {
      assert(BigInt(grouped.keys[block].size) <= m, `Too many ${block} slices for n=${n}`);
    }
    const ambient = vectors(n);
    let mismatches = 0;
    for (const x of ambient) {
      for (const y of ambient) {
        for (const z of ambient) {
          const reconstructed = mod3(
            evaluateTerms(grouped.groups.x, x, y, z) +
            evaluateTerms(grouped.groups.y, x, y, z) +
            evaluateTerms(grouped.groups.z, x, y, z)
          );
          if (reconstructed !== productPolynomial(x, y, z)) mismatches += 1;
        }
      }
    }
    assert(mismatches === 0, `Grouped expansion mismatch for n=${n}`);
    console.log(`n=${n}: ${terms.length} expanded terms grouped into ${grouped.keys.x.size}/${grouped.keys.y.size}/${grouped.keys.z.size} low-block slice keys`);
  }

  for (let n = 1; n <= 12; n += 1) {
    const cutoff = Math.floor(2 * n / 3);
    const byDP = monomialCountDP(n, cutoff);
    const byEnumeration = monomialCountEnumeration(n, cutoff);
    assert(byDP === byEnumeration, `Monomial counts disagree for n=${n}`);
    console.log(`n=${n}: cutoff ${cutoff}, m_n=${byDP}, 3m_n=${3n * byDP}, 3^n=${3n ** BigInt(n)}`);
  }

  const exactT = (Math.sqrt(33) - 1) / 8;
  const numericT = goldenMinimum(0.05, 0.99);
  const cFromMinimum = f(exactT);
  const cFromRadical = Math.cbrt(5589 + 891 * Math.sqrt(33)) / 8;
  assert(Math.abs(numericT - exactT) < 3e-8, 'Golden-section minimiser disagrees with analytic t');
  assert(Math.abs(f(numericT) - f(exactT)) < 1e-13, 'Numerical minimum has the wrong value');
  assert(Math.abs(cFromMinimum - cFromRadical) < 1e-14, 'Two routes to c disagree');
  assert(cFromMinimum.toFixed(15) === '2.755104613023633', 'Published decimal mismatch');
  assert(cFromMinimum < 3, 'Growth base is not below three');
  console.log(`minimum t=${exactT.toFixed(15)}, c=${cFromMinimum.toFixed(15)}, radical route=${cFromRadical.toFixed(15)}`);

  const max1 = maximumCapBySubset(1);
  const max2 = maximumCapBySubset(2);
  assert(max1 === 2, 'Exhaustive maximum for n=1 is not the published value 2');
  assert(max2 === 4, 'Exhaustive maximum for n=2 is not the published value 4');
  console.log(`external anchors recovered by subset search: maxima ${max1}, ${max2}`);

  const html = fs.readFileSync(PAGE, 'utf8');
  assert(attribute(html, 'data-published-c') === cFromMinimum.toFixed(15), 'Page constant c is stale');
  assert(attribute(html, 'data-small-maxima') === '2,4,9,20,45,112', 'Page small maxima changed');
  assert(attribute(html, 'data-default-m') === monomialCountDP(6).toString(), 'Page default m_6 is stale');
  assert(attribute(html, 'data-default-bound') === (3n * monomialCountDP(6)).toString(), 'Page default 3m_6 is stale');
  assert(attribute(html, 'data-default-base') === f(0.75).toFixed(15), 'Page default generating base is stale');
  assert(attribute(html, 'data-default-slices') === defaultSliceAnchor(3), 'Page default slice ledger is stale');
  assert(textById(html, 'mDP') === monomialCountDP(6).toString(), 'Visible default DP count is stale');
  assert(textById(html, 'mEnum') === monomialCountEnumeration(6).toString(), 'Visible default enumeration count is stale');
  assert(textById(html, 'threeM') === (3n * monomialCountDP(6)).toString(), 'Visible default bound is stale');
  assert(textById(html, 'wholeSpace') === (3n ** 6n).toString(), 'Visible default universe size is stale');
  assert(textById(html, 'baseReadout') === `base = ${f(0.75).toFixed(15)}`, 'Visible default base is stale');
  assert(textById(html, 'checkBase') === f(0.75).toFixed(15), 'Visible check-panel base is stale');
  assert(textById(html, 'lineCount') === '0', 'Visible default line count is stale');
  assert(textById(html, 'diagonalCount') === presetCap(3).length.toString(), 'Visible default diagonal count is stale');
  assert(textById(html, 'offCount') === '0', 'Visible default off-diagonal count is stale');
  const visibleSlices = [...html.matchAll(
    /<div class="slice"><b>[xyz] ledger<\/b><span>(\d+) terms<br \/>(\d+) distinct low blocks?<\/span><\/div>/g
  )].map((match) => [match[1], match[2]]);
  assert(visibleSlices.length === 3, 'Visible default slice ledger is incomplete');
  const visibleSliceAnchor = [
    visibleSlices.map((pair) => pair[0]).join(','),
    visibleSlices.map((pair) => pair[1]).join(',')
  ].join(';');
  assert(visibleSliceAnchor === defaultSliceAnchor(3), 'Visible default slice values are stale');
  const visibleMaxima = [...html.matchAll(/<div class="maximum"><b>(\d+)<\/b>/g)]
    .map((match) => match[1])
    .join(',');
  assert(visibleMaxima === '2,4,9,20,45,112', 'Visible published maxima changed');
  assert(html.includes(`= <span class="one">${cFromMinimum.toFixed(15)}</span>`), 'Visible minimum constant is stale');
  assert(html.includes('∛(5589+891√33)/8'), 'Visible algebraic constant is missing');
  console.log('page anchors: c=2.755104613023633, maxima=2,4,9,20,45,112, m_6=168, 3m_6=504');
  console.log(`page defaults: f(0.75)=${f(0.75).toFixed(15)}, slice ledger=${defaultSliceAnchor(3)}`);

  console.log(`PASS: ${checks} independent assertions`);
} catch (error) {
  console.error(`FAIL: ${error.message}`);
  process.exit(1);
}
