import { readFile } from 'node:fs/promises';

const HTML_URL = new URL('../../public/strata/mastermind-five-guesses/index.html', import.meta.url);
const EXPECTED = {
  codes: 1296,
  grades: 14,
  knuthOpening: '1122',
  knuthHistogram: [0, 1, 6, 62, 533, 694, 0],
  knuthTotal: 5801,
  knuthMax: 5,
  averageOpening: '1123',
  averageHistogram: [0, 1, 8, 86, 656, 544, 1],
  averageTotal: 5625,
  averageMax: 6,
  depthSix: ['4421'],
  constrainedHistogram: [0, 1, 8, 86, 654, 547, 0],
  constrainedTotal: 5626,
  constrainedMax: 5,
  logicalOnlyTotal: 5660,
  tableNodes: 937,
  illogicalNodes: 37,
  illogicalSecrets: 539,
  twiceIllogicalSecrets: 121,
  maxIllogical: 2
};

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

function same(actual, expected, label) {
  assert(
    JSON.stringify(actual) === JSON.stringify(expected),
    `${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`
  );
  console.log(`PASS ${label}: ${JSON.stringify(actual)}`);
}

function codeFromIndex(n) {
  let code = '';
  for (let p = 0; p < 4; p++) {
    code = String((n % 6) + 1) + code;
    n = Math.floor(n / 6);
  }
  return code;
}

function gradeText(guess, answer) {
  let black = 0;
  const guessCounts = [0, 0, 0, 0, 0, 0];
  const answerCounts = [0, 0, 0, 0, 0, 0];
  for (let i = 0; i < 4; i++) {
    if (guess[i] === answer[i]) {
      black++;
    } else {
      guessCounts[Number(guess[i]) - 1]++;
      answerCounts[Number(answer[i]) - 1]++;
    }
  }
  let white = 0;
  for (let colour = 0; colour < 6; colour++) {
    white += Math.min(guessCounts[colour], answerCounts[colour]);
  }
  return black * 5 + white;
}

function cleanTable(text) {
  return text.replace(/\s+/g, '').replace(/\*/g, '');
}

function makeParser(data) {
  function parseTable(text) {
    const source = cleanTable(text);
    let at = 0;

    function integer() {
      const start = at;
      while (/\d/.test(source[at] || '')) at++;
      assert(start !== at, `table integer expected at character ${at}`);
      return Number(source.slice(start, at));
    }

    function expression(candidateCount) {
      if (/[A-Z]/.test(source[at] || '')) {
        const label = source[at++];
        assert(data.labels[label], `unknown table label ${label}`);
        return parseTable(String(candidateCount) + data.labels[label]);
      }
      const node = { n: candidateCount };
      if (source[at] !== '(') return node;
      at++;
      node.g = source.slice(at, at + 4);
      assert(/^[1-6]{4}$/.test(node.g), `bad table guess at character ${at}`);
      at += 4;
      if (source[at] === ':') {
        at++;
        node.k = [];
        for (let index = 0; index < 14; index++) {
          node.k.push(expression(integer()));
          if (index < 13) {
            assert(
              source[at] === ',' || source[at] === ';',
              `table separator expected at character ${at}`
            );
            at++;
          }
        }
      }
      assert(source[at] === ')', `table close expected at character ${at}`);
      at++;
      return node;
    }

    const root = expression(integer());
    assert(at === source.length, `trailing table data at character ${at}`);
    return root;
  }
  return parseTable;
}

function lowerBound(codeCount) {
  if (codeCount <= 0) return 0;
  let remaining = codeCount;
  let capacity = 1;
  let depth = 1;
  let total = 0;
  while (remaining > 0) {
    const take = Math.min(remaining, capacity);
    total += take * depth;
    remaining -= take;
    capacity *= 13;
    depth++;
  }
  return total;
}

async function main() {
  const html = await readFile(HTML_URL, 'utf8');
  const jsonMatch = html.match(/<script id="kl-data" type="application\/json">([\s\S]*?)<\/script>/);
  assert(jsonMatch, 'embedded Koyama-Lai JSON was not found');
  const data = JSON.parse(jsonMatch[1]);
  const parseTable = makeParser(data);

  const codes = Array.from({ length: 6 ** 4 }, (_, index) => codeFromIndex(index));
  const codeIndex = new Map(codes.map((code, index) => [code, index]));
  same(codes.length, EXPECTED.codes, 'code space 6^4');
  same(new Set(codes).size, EXPECTED.codes, 'unique codes');

  const scores = [];
  const grades = new Set();
  for (let guess = 0; guess < codes.length; guess++) {
    const row = new Uint8Array(codes.length);
    for (let answer = 0; answer < codes.length; answer++) {
      row[answer] = gradeText(codes[guess], codes[answer]);
      grades.add(row[answer]);
    }
    scores.push(row);
  }
  same(grades.size, EXPECTED.grades, 'attainable black/white responses');
  console.log(`PASS scoring matrix: ${codes.length * codes.length} pairs recomputed`);

  function chooseMinimax(candidates) {
    if (candidates.length === 1) return candidates[0];
    const possible = new Uint8Array(codes.length);
    for (const candidate of candidates) possible[candidate] = 1;
    let bestWorst = Infinity;
    let bestPossible = -1;
    let bestAny = -1;
    for (let guess = 0; guess < codes.length; guess++) {
      const bins = new Uint16Array(25);
      const scoreRow = scores[guess];
      for (const answer of candidates) bins[scoreRow[answer]]++;
      let worst = 0;
      for (const count of bins) worst = Math.max(worst, count);
      if (worst < bestWorst) {
        bestWorst = worst;
        bestPossible = possible[guess] ? guess : -1;
        bestAny = guess;
      } else if (worst === bestWorst && possible[guess] && bestPossible < 0) {
        bestPossible = guess;
      }
    }
    return bestPossible >= 0 ? bestPossible : bestAny;
  }

  function buildKnuth() {
    const histogram = Array(8).fill(0);
    let nodes = 0;
    function build(candidates, depth) {
      nodes++;
      const guess = chooseMinimax(candidates);
      const node = { g: guess, n: candidates.length, children: new Map() };
      const bins = new Map();
      for (const answer of candidates) {
        if (answer === guess) {
          histogram[depth]++;
        } else {
          const response = scores[guess][answer];
          if (!bins.has(response)) bins.set(response, []);
          bins.get(response).push(answer);
        }
      }
      for (const [response, child] of bins) {
        node.children.set(response, build(child, depth + 1));
      }
      return node;
    }
    const all = Array.from({ length: codes.length }, (_, index) => index);
    const root = build(all, 1);
    return {
      root,
      histogram,
      total: histogram.reduce((sum, count, depth) => sum + count * depth, 0),
      max: histogram.reduce((last, count, depth) => count ? depth : last, 0),
      nodes
    };
  }

  const knuth = buildKnuth();
  same(codes[knuth.root.g], EXPECTED.knuthOpening, 'Knuth opening selected by minimax');
  same(knuth.histogram.slice(0, 7), EXPECTED.knuthHistogram, 'Knuth histogram');
  same(knuth.total, EXPECTED.knuthTotal, 'Knuth total guesses');
  same(knuth.max, EXPECTED.knuthMax, 'Knuth worst case');
  console.log(`PASS Knuth mean: ${knuth.total}/${codes.length} = ${(knuth.total / codes.length).toFixed(9)}`);

  function knuthCandidateTrace(secretCode) {
    const answer = codeIndex.get(secretCode);
    let candidates = Array.from({ length: codes.length }, (_, index) => index);
    let node = knuth.root;
    const counts = [];
    while (node) {
      counts.push(candidates.length);
      const response = scores[node.g][answer];
      if (response === 20) break;
      candidates = candidates.filter(candidate => scores[node.g][candidate] === response);
      node = node.children.get(response);
    }
    return counts;
  }
  same(knuthCandidateTrace('3631'), [1296, 256, 44, 7, 1], 'live five-row collapse for secret 3631');

  const smallStates = new Map();
  function auditTable(root) {
    const histogram = Array(8).fill(0);
    const depthSix = [];
    const paths = new Map();
    const illogicalCounts = new Map();
    let nodes = 0;
    let illogicalNodes = 0;
    let maxIllogical = 0;

    function visit(node, candidates, depth, history, illogical) {
      nodes++;
      assert(
        node.n === candidates.length,
        `table count ${node.n} disagrees with live count ${candidates.length} after ${history.join(' / ')}`
      );
      if (node.n === 0) return 0;
      if (node.n === 1) {
        histogram[depth]++;
        paths.set(candidates[0], history.concat([candidates[0]]));
        illogicalCounts.set(candidates[0], illogical);
        if (depth === 6) depthSix.push(candidates[0]);
        maxIllogical = Math.max(maxIllogical, illogical);
        return 1;
      }

      const guess = node.g;
      const logical = candidates.includes(guess);
      const nextIllogical = illogical + (logical ? 0 : 1);
      if (!logical) illogicalNodes++;
      const bins = new Map();
      for (const answer of candidates) {
        const response = gradeText(guess, answer);
        if (!bins.has(response)) bins.set(response, []);
        bins.get(response).push(answer);
      }

      let subtreeCost = candidates.length;
      const exact = bins.get(20) || [];
      for (const answer of exact) {
        histogram[depth]++;
        paths.set(answer, history.concat([guess]));
        illogicalCounts.set(answer, nextIllogical);
        maxIllogical = Math.max(maxIllogical, nextIllogical);
      }

      if (!node.k) {
        for (const [response, child] of bins) {
          if (response === 20) continue;
          assert(child.length === 1, `table shorthand ${node.n}(${guess}) failed`);
          histogram[depth + 1]++;
          subtreeCost += 1;
          paths.set(child[0], history.concat([guess, child[0]]));
          illogicalCounts.set(child[0], nextIllogical);
          if (depth + 1 === 6) depthSix.push(child[0]);
          maxIllogical = Math.max(maxIllogical, nextIllogical);
        }
      } else {
        for (let index = 0; index < data.order.length; index++) {
          const response = data.order[index];
          const child = bins.get(response) || [];
          if (response === 20) {
            assert(node.k[index].n === child.length, `perfect response count failed at ${guess}`);
          } else {
            subtreeCost += visit(
              node.k[index],
              child,
              depth + 1,
              history.concat([`${guess}:${Math.floor(response / 5)},${response % 5}`]),
              nextIllogical
            );
          }
        }
      }

      if (candidates.length >= 2 && candidates.length <= 8) {
        const key = candidates.join(',');
        if (!smallStates.has(key)) smallStates.set(key, { candidates: candidates.slice(), tableCost: subtreeCost });
      }
      return subtreeCost;
    }

    const total = visit(root, codes.slice(), 1, [], 0);
    return {
      histogram,
      total,
      max: histogram.reduce((last, count, depth) => count ? depth : last, 0),
      depthSix: depthSix.sort(),
      paths,
      nodes,
      illogicalNodes,
      maxIllogical,
      illogicalSecrets: [...illogicalCounts.values()].filter(count => count > 0).length,
      twiceIllogicalSecrets: [...illogicalCounts.values()].filter(count => count === 2).length
    };
  }

  const averageTree = parseTable(data.root);
  const average = auditTable(averageTree);
  same(averageTree.g, EXPECTED.averageOpening, 'expected-case opening');
  same(average.histogram.slice(0, 7), EXPECTED.averageHistogram, 'expected-case histogram');
  same(average.total, EXPECTED.averageTotal, 'expected-case total guesses');
  same(average.max, EXPECTED.averageMax, 'expected-case worst case');
  same(average.depthSix, EXPECTED.depthSix, 'depth-six secrets');
  same(average.nodes, EXPECTED.tableNodes, 'audited table situations');
  same(average.illogicalNodes, EXPECTED.illogicalNodes, 'ruled-out-guess situations');
  same(average.illogicalSecrets, EXPECTED.illogicalSecrets, 'secrets whose route uses a ruled-out guess');
  same(average.twiceIllogicalSecrets, EXPECTED.twiceIllogicalSecrets, 'secrets whose route uses two ruled-out guesses');
  same(average.maxIllogical, EXPECTED.maxIllogical, 'maximum ruled-out guesses on one route');
  console.log(`PASS expected-case mean: ${average.total}/${codes.length} = ${(average.total / codes.length).toFixed(9)}`);
  same(knuth.total - average.total, 176, 'aggregate guesses saved against Knuth\'s published tie rule');
  console.log(`PASS sole depth-six route: ${average.paths.get('4421').join(' -> ')}`);
  console.log(`PASS two-false-question example: ${average.paths.get('6312').join(' -> ')}`);

  const constrainedTree = structuredClone(averageTree);
  const vulnerableSubtree = constrainedTree.k[data.constrainedPath[0]].k[data.constrainedPath[1]];
  same(vulnerableSubtree.n, 39, 'vulnerable subtree candidates');
  constrainedTree.k[data.constrainedPath[0]].k[data.constrainedPath[1]] =
    parseTable(`39${data.labels[data.constrainedLabel]}`);
  const constrained = auditTable(constrainedTree);
  same(constrained.histogram.slice(0, 7), EXPECTED.constrainedHistogram, 'five-row histogram');
  same(constrained.total, EXPECTED.constrainedTotal, 'five-row total guesses');
  same(constrained.max, EXPECTED.constrainedMax, 'five-row worst case');
  same(constrained.total - average.total, 1, 'five-row constraint aggregate cost');
  console.log(`PASS five-row mean: ${constrained.total}/${codes.length} = ${(constrained.total / codes.length).toFixed(9)}`);

  same(
    Number((EXPECTED.logicalOnlyTotal / codes.length).toFixed(6)),
    4.367284,
    'published logical-only arithmetic'
  );
  console.log(
    `PASS logical-only penalty arithmetic: ${EXPECTED.logicalOnlyTotal} - ${average.total} = ` +
    `${EXPECTED.logicalOnlyTotal - average.total} guesses`
  );

  const exactMemo = new Map();
  let prunedEquivalentGuesses = 0;
  let prunedByBound = 0;

  function exactSmall(candidates) {
    if (candidates.length === 0) return 0;
    if (candidates.length === 1) return 1;
    const memoKey = candidates.join(',');
    if (exactMemo.has(memoKey)) return exactMemo.get(memoKey);
    const possible = new Uint8Array(codes.length);
    for (const candidate of candidates) possible[candidate] = 1;
    let best = Infinity;
    const partitionSignatures = new Set();

    for (let guess = 0; guess < codes.length; guess++) {
      const bins = new Map();
      let exact = false;
      for (const answer of candidates) {
        if (answer === guess) {
          exact = true;
          continue;
        }
        const response = scores[guess][answer];
        if (!bins.has(response)) bins.set(response, []);
        bins.get(response).push(answer);
      }
      if (!exact && bins.size === 1 && [...bins.values()][0].length === candidates.length) continue;
      const signature = `${exact ? guess : '-'}|` +
        [...bins.entries()]
          .sort((a, b) => a[0] - b[0])
          .map(([response, child]) => `${response}:${child.join('.')}`)
          .join('|');
      if (partitionSignatures.has(signature)) {
        prunedEquivalentGuesses++;
        continue;
      }
      partitionSignatures.add(signature);

      let optimistic = candidates.length;
      for (const child of bins.values()) optimistic += lowerBound(child.length);
      if (optimistic >= best) {
        prunedByBound++;
        continue;
      }

      let cost = candidates.length;
      const orderedChildren = [...bins.values()].sort((a, b) => b.length - a.length);
      for (const child of orderedChildren) {
        cost += exactSmall(child);
        if (cost >= best) {
          prunedByBound++;
          break;
        }
      }
      best = Math.min(best, cost);
    }
    exactMemo.set(memoKey, best);
    return best;
  }

  let certifiedSmallStates = 0;
  for (const { candidates, tableCost } of smallStates.values()) {
    const exactCost = exactSmall(candidates.map(code => codeIndex.get(code)));
    assert(
      exactCost === tableCost,
      `small-state branch-and-bound mismatch for ${candidates.join(',')}: table ${tableCost}, exact ${exactCost}`
    );
    certifiedSmallStates++;
  }
  console.log(
    `PASS exact branch-and-bound spot certificate: ${certifiedSmallStates} unique table states with 2 to 8 candidates`
  );
  console.log(
    `PASS search pruning: ${prunedEquivalentGuesses} response-equivalent guesses, ${prunedByBound} bound cuts`
  );

  assert(html.includes('5660 / 1296 = 4.367'), 'page is missing the logical-only benchmark');
  assert(html.trimEnd().endsWith('</script>\n</body>\n</html>'), 'load-bearing closing tags are incomplete');
  assert(!html.includes(String.fromCodePoint(8212)), 'em dash found in authored HTML');
  console.log('PASS page contract: benchmark present, no em dash, complete closing tags');

  console.log('');
  console.log('All executable checks passed.');
  console.log(
    'Scope note: this verifier audits the full published 5,625 tree and the 5,626 substitution. ' +
    'It re-runs exact branch-and-bound only on every encountered state of at most eight candidates. ' +
    'The global lower-bound search reported by Koyama and Lai is cited, not reproduced here.'
  );
}

main().catch(error => {
  console.error(`FAIL ${error.stack || error.message}`);
  process.exitCode = 1;
});
