import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
const PAGE_PATH = resolve(ROOT, 'public/strata/erdos-discrepancy/index.html');
const PAGE = readFileSync(PAGE_PATH, 'utf8');

let passed = 0;
function check(name, condition, detail) {
  if (!condition) {
    console.error(`FAIL  ${name}${detail ? `: ${detail}` : ''}`);
    process.exitCode = 1;
    return;
  }
  passed += 1;
  console.log(`PASS  ${name}${detail ? `: ${detail}` : ''}`);
}

/*
 * Independent transcription of Appendix B in Konev and Lisitsa,
 * Computer-Aided Proof of Erdos Discrepancy Properties, arXiv:1405.3097v2.
 * The paper prints 40 rows of 29 signs. Whitespace is not part of the object.
 */
const PAPER_ROWS = [
  '-++-+--++-++-+--+--++-+--+--+',
  '+-+--++-++-+-++--++-+---+-++-',
  '+--+--++++--+--++-+--++-++---',
  '-++-++-+-++--++-+-+---++-+--+',
  '+-++-+--++-+--+---+-++-+--++-',
  '++-+--+--++-++-+--++-+--+++-+',
  '-+----+++-+--+--+++---++-++-+',
  '--+--+++--+-+-+--+-+++-++-+--',
  '+--++-+--++-++-+--+--++--+++-',
  '--+++-+---++-+--++--+-+--+-++',
  '+-+--++-++-+--++-+--+--++-+--',
  '++--+-++-+-+--+-+-++-+--++-+-',
  '-+--++-+-+-++-+-+-++---+-+--+',
  '+++--+---++-+-++-+--++-+--+--',
  '++-+--++++--+---+-++++--+--++',
  '-++-+--++-+--+--++-+--++-++-+',
  '--++-+--+--++-++-+----+++-+--',
  '++--+++---+-++-+--+-++---+-++',
  '-++-+--+--++--++++-+--+--+--+',
  '+++--+--+++---++-++-+--++--+-',
  '+--+--++-++-+--+--+-+++-++-+-',
  '-+--++--+-++-++-+--+--+--++-+',
  '+-+--+++---++-+--++-++---+++-',
  '--++-++----+++--+-++-+--+--++',
  '-+--++-++-+-++--++--++----+++',
  '-++--++----++-+++--++---+++--',
  '--+-+-++-++-++-+-+----+++--++',
  '-+--++-++-+--+--+--++-+--++-+',
  '+-+--++--+-+--+-+-+-++++---+-',
  '+-++--+--+-+-+-++-+-+++--+-+-',
  '-+--+-+++--+-+++---++-+--+--+',
  '+-++--++---++-+-++--++-+---+-',
  '++-+--+-++--++-+--++-+--+-+++',
  '-+--++--+-+-+++--+-+--++-++-+',
  '--+--+-++---+-++-+-++--++-+--',
  '+++-+----++--+-++-+-++--++-+-',
  '-++-+-++--++-+---+-++-+--+++-',
  '---+-+-++--++-+--++-++-++-+--',
  '+--+--++++---++---+-+-++-+-++',
  '+--+-++--+-+--+-+-++---+++-++'
];

const paperWitness = PAPER_ROWS.join('');
check('published appendix has 40 rows', PAPER_ROWS.length === 40, `${PAPER_ROWS.length} rows`);
check(
  'every published row has 29 signs',
  PAPER_ROWS.every((row) => row.length === 29 && /^[+-]+$/.test(row)),
  PAPER_ROWS.map((row) => row.length).join(',')
);
check('published witness has 1160 signs', paperWitness.length === 1160, `${paperWitness.length} signs`);

const pageRowsMatch = PAGE.match(/const WITNESS_ROWS = (\[[\s\S]*?\]);/);
check('page exposes its witness rows to inspection', Boolean(pageRowsMatch));
let pageRows = [];
if (pageRowsMatch) {
  try {
    pageRows = JSON.parse(pageRowsMatch[1]);
  } catch (error) {
    console.error(`FAIL  page witness rows parse: ${error.message}`);
    process.exitCode = 1;
  }
}
const pageWitness = pageRows.join('');
check('page witness exactly matches the independent transcription', pageWitness === paperWitness);

const digest = createHash('sha256').update(paperWitness, 'utf8').digest('hex');
check(
  'page digest anchor matches the published sign string',
  PAGE.includes(`data-witness-digest="${digest}"`),
  `sha256 ${digest}`
);

function enumerateWitness(signString) {
  const x = [0, ...signString].map((sign) => sign === '+' ? 1 : sign === '-' ? -1 : 0);
  const n = signString.length;
  let maximum = 0;
  let tested = 0;
  const hits = [];
  const byStep = [];
  for (let d = 1; d <= n; d += 1) {
    let sum = 0;
    let stepMaximum = 0;
    for (let k = 1; k * d <= n; k += 1) {
      sum += x[k * d];
      tested += 1;
      const magnitude = Math.abs(sum);
      if (magnitude > maximum) {
        maximum = magnitude;
        hits.length = 0;
        hits.push({ d, k, sum, index: k * d });
      } else if (magnitude === maximum) {
        hits.push({ d, k, sum, index: k * d });
      }
      stepMaximum = Math.max(stepMaximum, magnitude);
    }
    byStep.push(stepMaximum);
  }
  return { maximum, tested, hits, byStep };
}

const witnessResult = enumerateWitness(paperWitness);
check('all homogeneous progression prefixes were enumerated', witnessResult.tested === 8374, `${witnessResult.tested} sums`);
check('published 1160-sign witness has discrepancy exactly 2', witnessResult.maximum === 2, `max |S(d,k)| = ${witnessResult.maximum}`);
check('page prints the independently derived prefix count', PAGE.includes('data-prefix-count="8374"'));
check('page prints the independently derived discrepancy', PAGE.includes('data-witness-maximum="2"'));
check(
  'page prints the independently derived maximum coordinates',
  witnessResult.hits.length === 894 &&
    witnessResult.hits[0].d === 1 &&
    witnessResult.hits[0].k === 12 &&
    witnessResult.hits[0].sum === 2 &&
    PAGE.includes('data-witness-hits="894"') &&
    PAGE.includes('data-first-maximum="1,12,2"'),
  `${witnessResult.hits.length} hits, first d=${witnessResult.hits[0].d}, k=${witnessResult.hits[0].k}, S=${witnessResult.hits[0].sum}`
);

let initialSum = 0;
let initialMaximum = 0;
for (let k = 1; k <= 20; k += 1) {
  initialSum += paperWitness[k * 7 - 1] === '+' ? 1 : -1;
  initialMaximum = Math.max(initialMaximum, Math.abs(initialSum));
}
check(
  'initial d=7,k=20 readout is derived from the witness',
  Math.floor(1160 / 7) === 165 &&
    initialSum === 0 &&
    initialMaximum === 2 &&
    PAGE.includes('S(7,20) = 0'),
  `max k 165, S = ${initialSum}, prefix max ${initialMaximum}`
);
check('paper row width shown on page is 29', PAGE.includes('29 signs per row'));
check('last nontrivial d for C=2 is 386', Math.floor(1160 / 3) === 386 && PAGE.includes('d = 386'));

function firstViolation(signs, C) {
  const n = signs.length;
  for (let d = 1; d <= n; d += 1) {
    let sum = 0;
    for (let k = 1; k * d <= n; k += 1) {
      sum += signs[k * d - 1];
      if (Math.abs(sum) > C) return { d, k, sum };
    }
  }
  return null;
}

function directSurvivors(C, N) {
  const survivors = [];
  for (let mask = 0; mask < 2 ** N; mask += 1) {
    const signs = Array.from({ length: N }, (_, i) => (mask & (1 << i)) ? 1 : -1);
    if (!firstViolation(signs, C)) survivors.push(mask);
  }
  return survivors;
}

/*
 * This exact-pattern blocking encoding is deliberately not the paper's sequential
 * counter encoding. For every (d,k), it emits one clause for each local sign
 * pattern whose sum exceeds C. The truth-table comparison below is independent:
 * it evaluates clauses as Boolean clauses, then compares with direct integer sums.
 */
function buildBlockingCnf(C, N) {
  const clauses = [];
  let prefixConstraints = 0;
  for (let d = 1; d <= N; d += 1) {
    const progression = [];
    for (let k = 1; k * d <= N; k += 1) {
      progression.push(k * d);
      prefixConstraints += 1;
      for (let mask = 0; mask < 2 ** k; mask += 1) {
        let sum = 0;
        const clause = [];
        for (let j = 0; j < k; j += 1) {
          const plus = Boolean(mask & (1 << j));
          sum += plus ? 1 : -1;
          clause.push(plus ? -progression[j] : progression[j]);
        }
        if (Math.abs(sum) > C) clauses.push(clause);
      }
    }
  }
  return { clauses, prefixConstraints };
}

function cnfSatisfied(clauses, assignmentMask) {
  return clauses.every((clause) => clause.some((literal) => {
    const variable = Math.abs(literal);
    const value = Boolean(assignmentMask & (1 << (variable - 1)));
    return literal > 0 ? value : !value;
  }));
}

for (const C of [1, 2, 3]) {
  for (let N = 4; N <= 12; N += 1) {
    const { clauses } = buildBlockingCnf(C, N);
    for (let mask = 0; mask < 2 ** N; mask += 1) {
      const signs = Array.from({ length: N }, (_, i) => (mask & (1 << i)) ? 1 : -1);
      const direct = firstViolation(signs, C) === null;
      const encoded = cnfSatisfied(clauses, mask);
      if (direct !== encoded) {
        console.error(`FAIL  CNF equivalence at C=${C}, N=${N}, assignment=${mask}`);
        process.exit(1);
      }
    }
  }
}
passed += 1;
console.log('PASS  exact-pattern CNF agrees with direct sums for every assignment on C=1..3, N=4..12');

const cnf12 = buildBlockingCnf(1, 12);
const sat11 = directSurvivors(1, 11);
const sat12 = directSurvivors(1, 12);
const displayedEleven = '+--+-++--++';
check('C=1,N=12 encoding has 35 prefix constraints', cnf12.prefixConstraints === 35, `${cnf12.prefixConstraints}`);
check('chosen C=1,N=12 encoding has 5734 clauses', cnf12.clauses.length === 5734, `${cnf12.clauses.length}`);
check('C=1,N=11 has a satisfying assignment', sat11.length > 0, `${sat11.length} survivor(s)`);
check(
  'rejected-step counterexample is a valid C=1,N=11 sequence',
  firstViolation(Array.from(displayedEleven, (sign) => sign === '+' ? 1 : -1), 1) === null &&
    PAGE.includes(displayedEleven),
  displayedEleven
);
check('C=1,N=12 is UNSAT by complete truth table', sat12.length === 0, `${2 ** 12} assignments rejected`);

function buildFullTreeRupStepCount(N) {
  let count = 0;
  for (let length = N; length >= 0; length -= 1) count += 2 ** length;
  return count;
}

const rupSteps = buildFullTreeRupStepCount(12);
check('full binary RUP refutation has 8191 clause additions', rupSteps === 8191, `${rupSteps} additions`);

function blockingClause(mask, length) {
  return Array.from({ length }, (_, index) => {
    const variable = index + 1;
    return mask & (1 << index) ? -variable : variable;
  });
}

function sameClause(a, b) {
  return a.length === b.length && a.every((literal, index) => literal === b[index]);
}

const cnfClauseSet = new Set(cnf12.clauses.map((clause) => clause.join(',')));
let acceptedRupSteps = 0;
let rupValid = true;
let previousLayer = [];
for (let mask = 0; mask < 2 ** 12; mask += 1) {
  const assignment = Array.from({ length: 12 }, (_, index) => mask & (1 << index) ? 1 : -1);
  const violation = firstViolation(assignment, 1);
  if (!violation) {
    rupValid = false;
    break;
  }
  const inputClause = [];
  for (let j = 1; j <= violation.k; j += 1) {
    const variable = j * violation.d;
    inputClause.push(assignment[variable - 1] > 0 ? -variable : variable);
  }
  if (!cnfClauseSet.has(inputClause.join(','))) {
    rupValid = false;
    break;
  }
  const leaf = blockingClause(mask, 12);
  const assumptionsFalsifyInput = inputClause.every((literal) => {
    const value = assignment[Math.abs(literal) - 1] > 0;
    return literal > 0 ? !value : value;
  });
  if (!assumptionsFalsifyInput) {
    rupValid = false;
    break;
  }
  previousLayer.push(leaf);
  acceptedRupSteps += 1;
}
for (let length = 11; rupValid && length >= 0; length -= 1) {
  const currentLayer = [];
  const pivot = length + 1;
  for (let mask = 0; mask < 2 ** length; mask += 1) {
    const parent = blockingClause(mask, length);
    const childA = previousLayer[mask];
    const childB = previousLayer[mask + 2 ** length];
    if (
      !sameClause(childA, [...parent, pivot]) ||
      !sameClause(childB, [...parent, -pivot])
    ) {
      rupValid = false;
      break;
    }
    currentLayer.push(parent);
    acceptedRupSteps += 1;
  }
  previousLayer = currentLayer;
}
check(
  'every miniature RUP leaf and resolution parent is valid',
  rupValid && acceptedRupSteps === 8191 && previousLayer.length === 1 && previousLayer[0].length === 0,
  `${acceptedRupSteps} accepted additions, final clause length ${previousLayer[0]?.length ?? 'missing'}`
);
check('page prints the C=1,N=12 assignment count', PAGE.includes('data-small-assignments="4096"'));
check('page prints the chosen CNF clause count', PAGE.includes('data-small-clauses="5734"'));
check('page prints the RUP addition count', PAGE.includes('data-rup-steps="8191"'));

const requiredPublishedAnchors = [
  'about 13 GB',
  'about 1.67 GB',
  '850.2 MB',
  'about five and a half hours'
];
for (const anchor of requiredPublishedAnchors) {
  check(`page labels published anchor ${anchor}`, PAGE.includes(anchor));
}

check(
  'page does not claim a local 1161 replay',
  PAGE.includes('1161 UNSAT: cited certificate not replayed in this session.')
);
check('page names homogeneous progressions', PAGE.includes('homogeneous arithmetic progression'));
check('page names the k=0 vacuous case', PAGE.includes('k = 0'));
check('page includes required closing tags', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(PAGE));

if (process.exitCode) {
  console.error(`\n${passed} checks passed before failure.`);
  process.exit(process.exitCode);
}

console.log(`\n${passed} checks passed.`);
console.log(`Witness: 1160 signs, sha256 ${digest}`);
console.log(`Witness scan: ${witnessResult.tested} prefix sums, max |S| = ${witnessResult.maximum}`);
console.log('Small proof: C=1,N=12, 5734 clauses, 4096 assignments rejected, 8191 RUP additions');
console.log('Large proof: cited only, no N=1161 artifact replay performed');
