// golay.mjs — construct the binary Golay codes from scratch and verify perfection.
//   node research/perfect-codes/golay.mjs
//
// Builds the EXTENDED binary Golay code G24 = [24,12,8] as [I_12 | B] over F2,
// where B is a bordered quadratic-residue (Paley) circulant on the projective
// line {∞,0,…,10}. We don't trust the construction blind: we search the small
// space of sign/border conventions and ACCEPT only a B whose 2^12 = 4096
// codewords realise the Golay weight enumerator exactly
//        A0=1, A8=759, A12=2576, A16=759, A24=1
// — which (with self-duality, doubly-even) uniquely characterises G24.
//
// Then we PUNCTURE one coordinate to get the perfect Golay code G23 = [23,12,7]
// and verify the sphere-packing perfection identity
//        2^12 · ( C(23,0)+C(23,1)+C(23,2)+C(23,3) ) = 2^12 · 2048 = 2^23,
// i.e. the 4096 balls of radius 3 tile F2^23 exactly (G23 corrects 3 errors).

const P = 11;
const QR = new Set([1, 3, 4, 5, 9]); // nonzero quadratic residues mod 11
const isQR = x => QR.has(((x % P) + P) % P);

const popcount = x => { let c = 0n; while (x) { c += x & 1n; x >>= 1n; } return Number(c); };

// Build candidate 12x12 border-QR matrix B under a convention.
// index 11 plays the role of ∞ (the border row/column).
function buildB({ form, diag, corner, border }) {
  const B = Array.from({ length: 12 }, () => new Array(12).fill(0));
  for (let i = 0; i < 11; i++) for (let j = 0; j < 11; j++) {
    if (i === j) { B[i][j] = diag; continue; }
    const t = form === 'sum' ? i + j : i - j;
    B[i][j] = isQR(t) ? 1 : 0;
  }
  for (let k = 0; k < 11; k++) { B[11][k] = border; B[k][11] = border; }
  B[11][11] = corner;
  return B;
}

// All 4096 codewords of [I|B]: each message m in {0,1}^12 maps to (m | m·B).
// Return weight enumerator and the codeword list (as BigInt bitmasks of length 24).
function codeFromB(B) {
  const rows = []; // generator rows as 24-bit BigInt masks: row r = e_r | B[r]
  for (let r = 0; r < 12; r++) {
    let mask = 1n << BigInt(r);             // identity part
    for (let c = 0; c < 12; c++) if (B[r][c]) mask |= 1n << BigInt(12 + c);
    rows.push(mask);
  }
  const words = new Array(4096);
  for (let m = 0; m < 4096; m++) {
    let w = 0n;
    for (let r = 0; r < 12; r++) if ((m >> r) & 1) w ^= rows[r];
    words[m] = w;
  }
  return { rows, words };
}

function weightEnum(words) {
  const A = {};
  for (const w of words) { const k = popcount(w); A[k] = (A[k] || 0) + 1; }
  return A;
}

const GOLAY24 = { 0: 1, 8: 759, 12: 2576, 16: 759, 24: 1 };
const eqEnum = (a, b) => {
  const ks = new Set([...Object.keys(a), ...Object.keys(b)]);
  for (const k of ks) if ((a[k] || 0) !== (b[k] || 0)) return false;
  return true;
};

let pass = 0, fail = 0;
const check = (c, m) => { (c ? pass++ : fail++); console.log((c ? '  ✓ ' : '  ✗ ') + m); };

console.log('Binary Golay codes from a bordered QR (Paley) construction over F2\n');

// --- search conventions for a valid G24 ---
let found = null;
for (const form of ['sum', 'diff'])
  for (const diag of [0, 1])
    for (const corner of [0, 1])
      for (const border of [0, 1]) {
        const B = buildB({ form, diag, corner, border });
        const { rows, words } = codeFromB(B);
        if (eqEnum(weightEnum(words), GOLAY24)) {
          found = { conv: { form, diag, corner, border }, B, rows, words };
          break;
        }
      }

check(!!found, found
  ? `found G24 via convention ${JSON.stringify(found.conv)} — weight enumerator matches Golay exactly`
  : 'NO convention produced the Golay [24,12,8] weight enumerator');

if (!found) { console.log(`\n${pass}/${pass + fail} checks passed.`); process.exit(1); }

const { B, rows, words } = found;
const A24 = weightEnum(words);
check(words.length === 4096, `G24 has 4096 = 2^12 codewords`);
check(eqEnum(A24, GOLAY24),
  `G24 weight enumerator A0=1, A8=759, A12=2576, A16=759, A24=1`);

// minimum distance = smallest nonzero weight (code is linear)
const nzWeights = words.map(w => popcount(w)).filter(x => x > 0);
check(Math.min(...nzWeights) === 8, `G24 minimum distance d = 8`);

// doubly-even: every weight divisible by 4
check(words.every(w => popcount(w) % 4 === 0), `G24 is doubly-even (all weights ≡ 0 mod 4)`);

// self-dual: every pair of generator rows is orthogonal over F2 (⇒ C = C^perp, dim 12)
let orth = true;
for (let a = 0; a < 12 && orth; a++)
  for (let b = 0; b < 12; b++) { if (popcount(rows[a] & rows[b]) % 2 !== 0) { orth = false; break; } }
check(orth, `G24 is self-dual (generator rows mutually orthogonal over F2) ⇒ dim = 12`);

// --- puncture coordinate 23 (the last) to get G23 = [23,12,7] ---
const mask23 = (1n << 23n) - 1n; // keep bits 0..22
const words23 = words.map(w => w & mask23); // drop top bit
// punctured code still has 4096 distinct words iff no two codewords differed only
// in the dropped coordinate — true because d(G24)=8 > 1.
const distinct23 = new Set(words23.map(String)).size;
check(distinct23 === 4096, `puncturing one coordinate keeps 4096 distinct words (d>1) ⇒ G23 = [23,12,7]`);

const nz23 = words23.map(w => popcount(w)).filter(x => x > 0);
check(Math.min(...nz23) === 7, `G23 minimum distance d = 7  ⇒ corrects t = 3 errors`);

// weight enumerator of G23 (the perfect code)
const A23 = weightEnum(words23);
const GOLAY23 = { 0: 1, 7: 253, 8: 506, 11: 1288, 12: 1288, 15: 506, 16: 253, 23: 1 };
check(eqEnum(A23, GOLAY23),
  `G23 weight enumerator A0=1,A7=253,A8=506,A11=1288,A12=1288,A15=506,A16=253,A23=1`);

// --- PERFECTION of G23: sphere-packing identity ---
const C = (n, k) => { let r = 1n; for (let i = 0; i < k; i++) r = r * BigInt(n - i) / BigInt(i + 1); return r; };
const ballR3 = C(23, 0) + C(23, 1) + C(23, 2) + C(23, 3); // 1 + 23 + 253 + 1771
check(ballR3 === 2048n, `radius-3 ball in F2^23 has 1+23+253+1771 = 2048 = 2^11 points`);
check(4096n * ballR3 === (1n << 23n),
  `PERFECT: 2^12 · 2048 = 2^23 = ${(1n << 23n)} — the 4096 radius-3 balls tile F2^23 exactly`);

console.log(`\nB (the 12×12 generator tail [I | B]) under convention ${JSON.stringify(found.conv)}:`);
for (const row of B) console.log('   ' + row.join(' '));

console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
