#!/usr/bin/env node

import { readFileSync } from "node:fs";

/*
 * Standalone verifier for /strata/vdj-repertoire/.
 *
 * This is deliberately dependency-free. It repeats the page's small, declared
 * event-key model from constants. Published benchmark conversions are checked
 * separately from toy-model results.
 */

const V_COUNT = 48;
const D_COUNT = 2;
const J_COUNT = 13;
const MAX_INSERTION = 22;
const LATENT_ALIASES = 32;
const HISTOGRAM_DRAWS = 20000;
const SHARING_DRAWS = 200000;
const UNIFORM_SEQUENCE_SPACE = 1e14;

function normalize(weights) {
  const total = weights.reduce((sum, value) => sum + value, 0);
  return weights.map((value) => value / total);
}

function geometricBins(stopProbability, maximum) {
  return Array.from({ length: maximum + 1 }, (_, length) =>
    length === maximum
      ? (1 - stopProbability) ** length
      : stopProbability * (1 - stopProbability) ** length
  );
}

const MODEL = {
  v: normalize(Array.from({ length: V_COUNT }, (_, i) => Math.exp(-i / 11))),
  d: [0.62, 0.38],
  j: normalize(Array.from({ length: J_COUNT }, (_, i) => Math.exp(-i / 4.5))),
  delV: [0.34, 0.28, 0.19, 0.12, 0.07],
  delD5: [0.44, 0.27, 0.17, 0.08, 0.04],
  delD3: [0.38, 0.29, 0.18, 0.10, 0.05],
  delJ: [0.36, 0.28, 0.20, 0.10, 0.06],
  insertionLength: geometricBins(0.17, MAX_INSERTION),
  base: [0.31, 0.21, 0.30, 0.18]
};

function shannon(probabilities) {
  return -probabilities.reduce(
    (sum, probability) => sum + (probability ? probability * Math.log2(probability) : 0),
    0
  );
}

function meanIndex(probabilities) {
  return probabilities.reduce((sum, probability, index) => sum + probability * index, 0);
}

function makeRng(seed) {
  let state = seed >>> 0;
  return function random() {
    state ^= state << 13;
    state ^= state >>> 17;
    state ^= state << 5;
    return (state >>> 0) / 4294967296;
  };
}

function choose(probabilities, random) {
  let cursor = random();
  for (let i = 0; i < probabilities.length; i += 1) {
    cursor -= probabilities[i];
    if (cursor < 0) return i;
  }
  return probabilities.length - 1;
}

function mix(hash, value) {
  let next = (hash ^ ((value + 0x9e3779b9 + (hash << 6) + (hash >>> 2)) >>> 0)) >>> 0;
  next = Math.imul(next ^ (next >>> 16), 0x45d9f3b) >>> 0;
  return (next ^ (next >>> 16)) >>> 0;
}

function eventHash(fixed, insertedBases) {
  let h1 = 0x811c9dc5;
  let h2 = 0x27d4eb2f;
  for (const value of fixed) {
    h1 = mix(h1, value + 1);
    h2 = mix(h2, value + 101);
  }
  for (let junction = 0; junction < insertedBases.length; junction += 1) {
    for (const base of insertedBases[junction]) {
      h1 = mix(h1, base + 11 + junction * 7);
      h2 = mix(h2, base + 211 + junction * 13);
    }
  }
  return (h1 & 0x1fffff) * 4294967296 + h2;
}

function sample(random) {
  const v = choose(MODEL.v, random);
  const d = choose(MODEL.d, random);
  const j = choose(MODEL.j, random);
  const delV = choose(MODEL.delV, random);
  const delD5 = choose(MODEL.delD5, random);
  const delD3 = choose(MODEL.delD3, random);
  const delJ = choose(MODEL.delJ, random);
  const n1 = choose(MODEL.insertionLength, random);
  const n2 = choose(MODEL.insertionLength, random);
  const alias = Math.floor(random() * LATENT_ALIASES);

  let keyProbability = MODEL.v[v] * MODEL.d[d] * MODEL.j[j]
    * MODEL.delV[delV] * MODEL.delD5[delD5]
    * MODEL.delD3[delD3] * MODEL.delJ[delJ]
    * MODEL.insertionLength[n1] * MODEL.insertionLength[n2];
  const fixed = [v, d, j, delV, delD5, delD3, delJ, n1, n2];
  const insertedBases = [[], []];

  for (let junction = 0; junction < 2; junction += 1) {
    const length = junction === 0 ? n1 : n2;
    for (let i = 0; i < length; i += 1) {
      const base = choose(MODEL.base, random);
      keyProbability *= MODEL.base[base];
      insertedBases[junction].push(base);
    }
  }

  // The latent alias is deliberately not part of the event-description key.
  // Marginalizing its 32 equiprobable values cancels its 1/32 factor in Pkey.
  // Other event descriptions that render the same nucleotide string are not
  // collapsed, so this is not nucleotide-sequence Pgen.
  void alias;
  const key = eventHash(fixed, insertedBases);
  return { keyProbability, key };
}

let passed = 0;
let failed = 0;

function check(label, value, predicate, rendered = String(value)) {
  if (predicate(value)) {
    passed += 1;
    console.log(`PASS ${label}: ${rendered}`);
  } else {
    failed += 1;
    console.error(`FAIL ${label}: ${rendered}`);
  }
}

function closeTo(expected, tolerance = 1e-9) {
  return (value) => Math.abs(value - expected) <= tolerance;
}

function displaysAs(expected, digits) {
  return (value) => value.toFixed(digits) === expected;
}

const page = readFileSync(
  new URL("../../public/strata/vdj-repertoire/index.html", import.meta.url),
  "utf8"
);

for (const phrase of [
  "Event-key probability, Pkey",
  "Sample space: hashes of full event descriptions",
  "upper bound on nucleotide-string support",
  "distinct shared event-description hashes",
  "It is not Pgen of the displayed nucleotide string",
  "event-hash sharing is a lower bound on rendered-sequence sharing"
]) {
  check(`page states event-key contract: ${phrase}`, page, (value) => value.includes(phrase), phrase);
}

const BASES = ["A", "C", "G", "T"];
const vEnd = "TGTGCCAAAGAC";
const dCore = "GGGACAGGG";
const jStart = "AAAATTTGGG";
const renderedA = vEnd + dCore + jStart;
const renderedB = vEnd.slice(0, -1) + BASES[1] + dCore + jStart;
const fixedA = [0, 0, 0, 0, 0, 0, 0, 0, 0];
const fixedB = [0, 0, 0, 1, 0, 0, 0, 1, 0];
const collisionA = eventHash(fixedA, [[], []]);
const collisionB = eventHash(fixedB, [[1], []]);
check(
  "known convergent descriptions render the same nucleotide string",
  renderedA === renderedB,
  (value) => value === true,
  `${renderedA} = ${renderedB}`
);
check(
  "known convergent descriptions remain separate event hashes",
  collisionA !== collisionB,
  (value) => value === true,
  `${collisionA} != ${collisionB}`
);

for (const [name, probabilities] of Object.entries(MODEL)) {
  check(
    `${name} probabilities sum to one`,
    probabilities.reduce((sum, value) => sum + value, 0),
    closeTo(1, 1e-12),
    probabilities.reduce((sum, value) => sum + value, 0).toFixed(12)
  );
}

const segmentProduct = V_COUNT * D_COUNT * J_COUNT;
check("segment product", segmentProduct, (value) => value === 1248, "48 × 2 × 13 = 1,248");

const segmentEntropy = shannon(MODEL.v) + shannon(MODEL.d) + shannon(MODEL.j);
const deletionEntropy = shannon(MODEL.delV) + shannon(MODEL.delD5)
  + shannon(MODEL.delD3) + shannon(MODEL.delJ);
const insertionLengthMean = meanIndex(MODEL.insertionLength);
const oneJunctionEntropy = shannon(MODEL.insertionLength)
  + insertionLengthMean * shannon(MODEL.base);
const insertionEntropy = 2 * oneJunctionEntropy;
const eventKeyEntropy = segmentEntropy + deletionEntropy + insertionEntropy;
const aliasedScenarioEntropy = eventKeyEntropy + Math.log2(LATENT_ALIASES);
const effectiveEventKeyDiversity = 2 ** eventKeyEntropy;

check("segment-choice entropy", segmentEntropy, closeTo(9.048440023638, 1e-9), `${segmentEntropy.toFixed(6)} bits`);
check("deletion entropy", deletionEntropy, closeTo(8.204162006523, 1e-9), `${deletionEntropy.toFixed(6)} bits`);
check("one-junction insertion entropy", oneJunctionEntropy, closeTo(13.229864630472, 1e-9), `${oneJunctionEntropy.toFixed(6)} bits`);
check("entropy with latent alias", aliasedScenarioEntropy, closeTo(48.712331291105, 1e-9), `${aliasedScenarioEntropy.toFixed(6)} bits`);
check("event-key entropy after alias marginalization", eventKeyEntropy, closeTo(43.712331291105, 1e-9), `${eventKeyEntropy.toFixed(6)} bits`);
check(
  "toy event-key Shannon diversity",
  effectiveEventKeyDiversity,
  (value) => value.toExponential(3) === "1.441e+13",
  effectiveEventKeyDiversity.toExponential(4)
);

const stringsPerJunction = (4n ** BigInt(MAX_INSERTION + 1) - 1n) / 3n;
const support = BigInt(segmentProduct) * 5n ** 4n * stringsPerJunction ** 2n;
const supportLog10 = Math.log10(Number(support.toString().slice(0, 15)))
  + support.toString().length - 15;
check(
  "capped event-key support",
  support,
  (value) => value === 429152546952252964716038935980000n,
  `${support.toString()} event keys`
);
check("capped event-key support log10", supportLog10, displaysAs("32.633", 3), supportLog10.toFixed(3));

function maxOf(probabilities) {
  return Math.max(...probabilities);
}

function minOf(probabilities) {
  return Math.min(...probabilities);
}

const maximumPkey = maxOf(MODEL.v) * maxOf(MODEL.d) * maxOf(MODEL.j)
  * maxOf(MODEL.delV) * maxOf(MODEL.delD5) * maxOf(MODEL.delD3) * maxOf(MODEL.delJ)
  * maxOf(MODEL.insertionLength) ** 2;
const minimumPkey = minOf(MODEL.v) * minOf(MODEL.d) * minOf(MODEL.j)
  * minOf(MODEL.delV) * minOf(MODEL.delD5) * minOf(MODEL.delD3) * minOf(MODEL.delJ)
  * MODEL.insertionLength[MAX_INSERTION] ** 2
  * minOf(MODEL.base) ** (2 * MAX_INSERTION);
const fullPkeySpan = Math.log10(maximumPkey / minimumPkey);
check("toy Pkey support span", fullPkeySpan, displaysAs("41.403", 3), `${fullPkeySpan.toFixed(3)} orders`);

const firstEventKey = sample(makeRng(0xc0ffee11));
check(
  "seeded first event-key Pkey",
  firstEventKey.keyProbability,
  closeTo(1.318351e-12, 1e-18),
  `${firstEventKey.keyProbability.toExponential(6)}, ${(-Math.log2(firstEventKey.keyProbability)).toFixed(4)} bits`
);

const histogramRng = makeRng(0x5eed1234);
let informationSum = 0;
let sampledMinPkey = Infinity;
let sampledMaxPkey = 0;
for (let i = 0; i < HISTOGRAM_DRAWS; i += 1) {
  const { keyProbability } = sample(histogramRng);
  informationSum += -Math.log2(keyProbability);
  sampledMinPkey = Math.min(sampledMinPkey, keyProbability);
  sampledMaxPkey = Math.max(sampledMaxPkey, keyProbability);
}
const sampledEntropy = informationSum / HISTOGRAM_DRAWS;
const sampledSpan = Math.log10(sampledMaxPkey / sampledMinPkey);
check("seeded sampled event-key entropy", sampledEntropy, displaysAs("43.5521", 4), `${sampledEntropy.toFixed(4)} bits from ${HISTOGRAM_DRAWS.toLocaleString("en-US")} draws`);
check("seeded sampled Pkey span", sampledSpan, displaysAs("31.552", 3), `${sampledSpan.toFixed(3)} orders`);

const firstRng = makeRng(0xa11ce001);
const secondRng = makeRng(0xb0b00002);
const firstRepertoire = new Set();
for (let i = 0; i < SHARING_DRAWS; i += 1) {
  firstRepertoire.add(sample(firstRng).key);
}
const sharedKeys = new Set();
for (let i = 0; i < SHARING_DRAWS; i += 1) {
  const key = sample(secondRng).key;
  if (firstRepertoire.has(key)) sharedKeys.add(key);
}
const modelShared = sharedKeys.size;
const uniformShared = SHARING_DRAWS ** 2 / UNIFORM_SEQUENCE_SPACE;
const sharingRatio = modelShared / uniformShared;
check("seeded shared event-description hashes", modelShared, (value) => value === 682, `${modelShared.toLocaleString("en-US")} distinct shared event hashes at N = ${SHARING_DRAWS.toLocaleString("en-US")}`);
check("uniform null", uniformShared, closeTo(0.0004, 1e-12), `${uniformShared.toFixed(4)} expected shared sequences`);
check("million-draw uniform null", 1e6 ** 2 / UNIFORM_SEQUENCE_SPACE, closeTo(0.01, 1e-12), "0.01 expected shared sequences");
check("event-hash sharing excess over uniform sequence null", sharingRatio, (value) => value.toExponential(3) === "1.705e+6", `${sharingRatio.toExponential(3)} ×`);

for (const [label, bits, expected] of [
  ["published TCR-beta 43-bit conversion", 43, 8.796093022208e12],
  ["published TCR-beta 47-bit conversion", 47, 1.40737488355328e14],
  ["published post-selection 38-bit conversion", 38, 2.74877906944e11],
  ["published TCR-alpha 30-bit conversion", 30, 1.073741824e9],
  ["published IGH 70-bit conversion", 70, 1.1805916207174113e21]
]) {
  const diversity = 2 ** bits;
  check(label, diversity, closeTo(expected, expected * 1e-12), `${bits} bits → ${diversity.toExponential(4)}`);
}

console.log(`\n${passed} passed, ${failed} failed`);
process.exit(failed === 0 ? 0 : 1);
