#!/usr/bin/env node

import { readFileSync } from "node:fs";

/*
 * Standalone verifier for /strata/grundy-periodicity/.
 *
 * No tables are used to produce either sequence. Dawson's chess is generated
 * from the octal digits .137. Grundy's game is generated from every unequal
 * split, with the sparse/common parity identity used only to partition that
 * complete move set efficiently.
 */

const DAWSON_HORIZON = 1200;
const GRUNDY_HORIZON = 1_000_003;
const SCAN_N0 = 8192;
const SCAN_BOUND = 512;
const WINDOW_K = 3;
const EXPECTED_DAWSON_EXCEPTIONS = [0, 14, 16, 17, 31, 34, 51];
const EXPECTED_GRUNDY_SPARSE_COUNT = 1274;
const EXPECTED_GRUNDY_LAST_SPARSE = { index: 82_860, value: 108 };
const EXPECTED_GRUNDY_MAXIMUM = 231;

/*
 * Cited historical constants, not results reproduced by this program.
 * Primary source: Achim Flammenkamp, "Sprague-Grundy Values of Grundy's Game"
 * https://wwwhomes.uni-bielefeld.de/achim/grundy.html
 * It lists G(48399022)=259, summarizes "sparse=1287 last=48399022", and
 * reports that the 2012 run reached G(284944236543) on 25 November 2012.
 */
const FLAMMENKAMP_RECORD = {
  frontier: 284_944_236_543,
  sparseCount: 1_287,
  lastSparse: { index: 48_399_022, value: 259 }
};

const A002187_FIXTURE = [
  0,1,1,2,0,3,1,1,0,3,3,2,2,4,0,5,2,2,3,3,0,1,1,3,0,2,
  1,1,0,4,5,2,7,4,0,1,1,2,0,3,1,1,0,3,3,2,2,4,4,5,5,2,
  3,3,0,1,1,3,0,2,1,1,0,4,5,3,7,4,8,1,1,2,0,3,1,1,0,3,
  3,2,2,4,4,5,5,9,3,3,0,1,1,3,0,2,1,1,0,4,5,3,7,4,8,1
];

const A002188_FIXTURE = [
  0,0,0,1,0,2,1,0,2,1,0,2,1,3,2,1,3,2,4,3,0,4,3,0,4,3,
  0,4,1,2,3,1,2,4,1,2,4,1,2,4,1,5,4,1,5,4,1,5,4,1,0,2,
  1,0,2,1,5,2,1,3,2,1,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,
  2,4,5,2,4,5,2,4,3,7,4,3,7,4,3,7,4,3,5,2,3,5,2,3,5,2
];

function assert(condition, label, detail = "") {
  if (!condition) {
    throw new Error(`FAIL  ${label}${detail ? `: ${detail}` : ""}`);
  }
  console.log(`PASS  ${label}${detail ? `: ${detail}` : ""}`);
}

function sameArray(actual, expected) {
  return actual.length === expected.length &&
    actual.every((value, index) => value === expected[index]);
}

function mexFromMarks(marks) {
  let value = 0;
  while (marks[value]) value++;
  return value;
}

function computeOctal(codeDigits, horizon) {
  const g = new Uint16Array(horizon + 1);
  for (let n = 1; n <= horizon; n++) {
    const reachable = new Uint8Array(1024);
    for (let take = 1; take <= codeDigits.length; take++) {
      const digit = codeDigits[take - 1];
      const remainder = n - take;
      if (remainder < 0 || digit === 0) continue;
      if (remainder === 0 && (digit & 1)) reachable[0] = 1;
      if (remainder > 0 && (digit & 2)) reachable[g[remainder]] = 1;
      if (remainder >= 2 && (digit & 4)) {
        for (let a = 1; a <= Math.floor(remainder / 2); a++) {
          reachable[g[a] ^ g[remainder - a]] = 1;
        }
      }
    }
    g[n] = mexFromMarks(reachable);
  }
  return g;
}

function sparseValue(value) {
  let upperBits = value >>> 1;
  let parity = 0;
  while (upperBits) {
    parity ^= upperBits & 1;
    upperBits >>>= 1;
  }
  return parity === 0;
}

function computeGrundyNaive(horizon) {
  const g = new Uint16Array(horizon + 1);
  const marks = new Int32Array(1024);
  for (let n = 3; n <= horizon; n++) {
    for (let a = 1; a < n - a; a++) {
      marks[g[a] ^ g[n - a]] = n;
    }
    let value = 0;
    while (marks[value] === n) value++;
    g[n] = value;
  }
  return g;
}

/*
 * Exact sparse-space acceleration.
 *
 * Let q(x) be the parity of the one-bits of x after deleting its low bit.
 * q is linear under XOR. Values with q=0 are sparse and values with q=1
 * are common. Therefore:
 *
 *   sparse XOR common = common
 *   common XOR common = sparse
 *   sparse XOR sparse = sparse
 *
 * The first pass visits every legal split with at least one sparse side.
 * It therefore sees every reachable common value. If c is the least common
 * value not seen, mex is at most c. The second pass need only test the still
 * missing sparse values below c against common/common splits. No move is
 * discarded, and the result is the same mex as the quadratic recurrence.
 */
function computeGrundy(horizon, onProgress = null) {
  const g = new Uint16Array(horizon + 1);
  const sparseAt = new Uint8Array(horizon + 1);
  const sparsePositions = new Uint32Array(horizon + 1);
  const valueIsSparse = new Uint8Array(1024);
  const reachStamp = new Int32Array(1024);
  const activeStamp = new Int32Array(1024);
  const candidates = new Uint16Array(1024);

  for (let value = 0; value < valueIsSparse.length; value++) {
    valueIsSparse[value] = sparseValue(value) ? 1 : 0;
  }

  sparseAt[0] = sparseAt[1] = sparseAt[2] = 1;
  let sparsePositionCount = 2;
  sparsePositions[0] = 1;
  sparsePositions[1] = 2;
  let maximum = 0;

  for (let n = 3; n <= horizon; n++) {
    for (let q = 0; q < sparsePositionCount; q++) {
      const a = sparsePositions[q];
      if (a >= n) break;
      const b = n - a;
      if (b < 1 || a === b) continue;
      reachStamp[g[a] ^ g[b]] = n;
    }

    let firstMissingCommon = 0;
    while (valueIsSparse[firstMissingCommon] ||
           reachStamp[firstMissingCommon] === n) {
      firstMissingCommon++;
    }

    let candidateCount = 0;
    for (let value = 0; value < firstMissingCommon; value++) {
      if (valueIsSparse[value] && reachStamp[value] !== n) {
        candidates[candidateCount++] = value;
        activeStamp[value] = n;
      }
    }

    let remaining = candidateCount;
    const splitLimit = (n - 1) >>> 1;
    for (let a = 1; a <= splitLimit && remaining; a++) {
      const b = n - a;
      if (sparseAt[a] || sparseAt[b]) continue;
      const option = g[a] ^ g[b];
      if (option < firstMissingCommon && activeStamp[option] === n) {
        activeStamp[option] = 0;
        remaining--;
      }
    }

    let result = firstMissingCommon;
    for (let q = 0; q < candidateCount; q++) {
      const value = candidates[q];
      if (activeStamp[value] === n) {
        result = value;
        break;
      }
    }

    g[n] = result;
    if (result > maximum) maximum = result;
    if (valueIsSparse[result]) {
      sparseAt[n] = 1;
      sparsePositions[sparsePositionCount++] = n;
    }

    if (onProgress && n % 100_000 === 0) {
      onProgress(n, sparsePositionCount + 1, maximum);
    }
  }

  return {
    g,
    sparseAt,
    sparseCount: sparsePositionCount + 1,
    maximum
  };
}

function scanCertificateShape(g, n0, periodBound, k) {
  const failures = [];
  for (let period = 1; period <= periodBound; period++) {
    const end = 2 * n0 + period + k;
    let firstFailure = -1;
    for (let n = n0; n < end; n++) {
      if (g[n + period] !== g[n]) {
        firstFailure = n;
        break;
      }
    }
    failures.push({ period, firstFailure, end });
  }
  return failures;
}

function lastSparseOccurrence(g, sparseAt) {
  for (let n = g.length - 1; n >= 0; n--) {
    if (sparseAt[n]) return { index: n, value: g[n] };
  }
  return { index: -1, value: -1 };
}

try {
  console.log("Recomputing Dawson's chess .137 from its three octal digits");
  const dawson = computeOctal([1, 3, 7], DAWSON_HORIZON + 34);

  assert(
    sameArray(Array.from(dawson.slice(0, A002187_FIXTURE.length)), A002187_FIXTURE),
    "Dawson prefix matches the independent OEIS A002187 fixture",
    `${A002187_FIXTURE.length}/${A002187_FIXTURE.length} terms`
  );

  const exceptions = [];
  for (let n = 0; n < 52; n++) {
    const eventualTemplateValue = dawson[68 + (n % 34)];
    if (dawson[n] !== eventualTemplateValue) exceptions.push(n);
  }
  assert(
    sameArray(exceptions, EXPECTED_DAWSON_EXCEPTIONS),
    "exceptions to the eventual 34-residue template",
    `{${exceptions.join(",")}}`
  );

  const certificateChecks = [];
  for (let n = 52; n < 2 * 52 + 34 + 3; n++) {
    certificateChecks.push(dawson[n + 34] === dawson[n]);
  }
  assert(
    certificateChecks.length === 89 && certificateChecks.every(Boolean),
    "Guy-Smith window [52,141) passes",
    "89/89 equalities"
  );

  let dawsonTailMatches = 0;
  let dawsonTailChecks = 0;
  let dawsonTailFailure = -1;
  for (let n = 52; n + 34 <= DAWSON_HORIZON; n++) {
    dawsonTailChecks++;
    if (dawson[n + 34] === dawson[n]) {
      dawsonTailMatches++;
    } else if (dawsonTailFailure < 0) {
      dawsonTailFailure = n;
    }
  }
  assert(
    dawsonTailFailure < 0,
    `period-34 tail through n=${DAWSON_HORIZON}`,
    `${dawsonTailMatches}/${dawsonTailChecks} computed equalities`
  );

  console.log(
    `Recomputing Grundy's game through n=${GRUNDY_HORIZON.toLocaleString("en-US")}`
  );
  const naivePrefix = computeGrundyNaive(4096);
  const grundy = computeGrundy(
    GRUNDY_HORIZON,
    (n, sparseCount, maximum) => {
      console.log(
        `INFO  Grundy n=${n.toLocaleString("en-US")}, ` +
        `sparse=${sparseCount.toLocaleString("en-US")}, max=${maximum}`
      );
    }
  );

  assert(
    sameArray(Array.from(grundy.g.slice(0, naivePrefix.length)), Array.from(naivePrefix)),
    "sparse-space accelerator matches direct unequal-split mex",
    "4097/4097 terms"
  );
  assert(
    sameArray(Array.from(grundy.g.slice(0, A002188_FIXTURE.length)), A002188_FIXTURE),
    "Grundy prefix matches the independent OEIS A002188 fixture",
    `${A002188_FIXTURE.length}/${A002188_FIXTURE.length} terms`
  );

  const scan = scanCertificateShape(
    grundy.g,
    SCAN_N0,
    SCAN_BOUND,
    WINDOW_K
  );
  assert(
    scan.every(item => item.firstFailure >= 0),
    "every Grundy candidate period fails the certificate-shaped window",
    `${SCAN_BOUND}/${SCAN_BOUND} periods, n0=${SCAN_N0}, k-shaped=${WINDOW_K}`
  );

  let recomputedSparseCount = 0;
  for (let n = 0; n <= GRUNDY_HORIZON; n++) {
    if (sparseValue(grundy.g[n])) recomputedSparseCount++;
  }
  assert(
    recomputedSparseCount === grundy.sparseCount &&
    recomputedSparseCount === EXPECTED_GRUNDY_SPARSE_COUNT,
    "sparse occurrences in the verified Grundy prefix",
    `${recomputedSparseCount.toLocaleString("en-US")} through n=${GRUNDY_HORIZON.toLocaleString("en-US")}`
  );

  const lastSparse = lastSparseOccurrence(grundy.g, grundy.sparseAt);
  assert(
    lastSparse.index === EXPECTED_GRUNDY_LAST_SPARSE.index &&
    lastSparse.value === EXPECTED_GRUNDY_LAST_SPARSE.value,
    "last sparse occurrence in verified prefix",
    `G(${lastSparse.index.toLocaleString("en-US")})=${lastSparse.value}`
  );
  assert(
    grundy.maximum === EXPECTED_GRUNDY_MAXIMUM,
    "maximum Grundy value in verified prefix",
    String(grundy.maximum)
  );

  const pageSource = readFileSync(
    new URL("../../public/strata/grundy-periodicity/index.html", import.meta.url),
    "utf8"
  );
  const citedSparseCount = FLAMMENKAMP_RECORD.sparseCount.toLocaleString("en-US");
  const citedSparsePair =
    `G(${FLAMMENKAMP_RECORD.lastSparse.index.toLocaleString("en-US")})=` +
    FLAMMENKAMP_RECORD.lastSparse.value;
  const citedFrontier = FLAMMENKAMP_RECORD.frontier.toLocaleString("en-US");
  const citedSparsePairOccurrences = pageSource.split(citedSparsePair).length - 1;
  assert(
    pageSource.includes(`<strong>${citedSparseCount}</strong> sparse occurrences`) &&
    pageSource.includes(
      `<output>${citedFrontier} ~= 2^38.1<br />` +
      `last cited sparse: ${citedSparsePair}</output>`
    ) &&
    citedSparsePairOccurrences === 2,
    "page matches the cited Flammenkamp record constants",
    `${citedSparseCount} sparse occurrences; last ${citedSparsePair}; ` +
    `frontier ${citedFrontier}`
  );

  const publishedFrontier = FLAMMENKAMP_RECORD.frontier;
  const frontierPower = Math.log2(publishedFrontier);
  assert(
    frontierPower.toFixed(1) === "38.1",
    "published frontier magnitude conversion",
    `${publishedFrontier.toLocaleString("en-US")} = 2^${frontierPower.toFixed(3)} ~= 2^38.1`
  );
  assert(
    2 * 52 + 34 + 3 === 141,
    "Dawson certificate upper endpoint",
    "2*52+34+3=141"
  );
  assert(
    328_226_140_474 > publishedFrontier &&
    465_384_263_797 > publishedFrontier,
    "reported .106 scales exceed the Grundy computation frontier",
    "period=328,226,140,474; preperiod=465,384,263,797"
  );

  console.log("ALL CHECKS PASSED");
  process.exit(0);
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
