// WHICH ASSERTION FAILS IF THE ANSWER IS SIMPLY WRONG?
// Assertions 3 through 8 recount the published fixture without using the page display code.
// Assertion 9 feeds that answer to the unmodified certificate check. Assertions 12 and 13
// replace one player in one round and require the real checker to name the exact broken pairs.
// Assertions 15 through 25 doctor one value in serialised certificate text and require the
// named production assertion to fail. A wrong matrix, attendance count, total, spread or
// classification therefore has a direct red control.

import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import {
  analyseSchedule, certificateData, defineScheduleCertificate, parseSchedule,
} from '../../public/tools/schedule-check/engine.mjs';

const kitSource = readFileSync(new URL('../../public/_kit/certificate.js', import.meta.url), 'utf8');
const sandbox = { window: {} };
vm.runInContext(kitSource, vm.createContext(sandbox));
const C = sandbox.window.AW.certificate;
defineScheduleCertificate(C);

let passed = 0;
let failed = 0;
let assertionNumber = 0;
function test(name, fn) {
  assertionNumber++;
  try {
    fn();
    passed++;
    console.log(`${assertionNumber}. PASS ${name}`);
  } catch (error) {
    failed++;
    console.log(`${assertionNumber}. FAIL ${name}: ${error.message}`);
  }
}

const fixture = readFileSync(new URL('./fixtures/wiseman-five.txt', import.meta.url), 'utf8');
const roster = 'A\nB\nC\nD\nE';
const parsed = parseSchedule(fixture, roster);
const answer = analyseSchedule(parsed, 'perfect-whist');
const cert = C.make('doubles-schedule-check', certificateData(answer));
const text = C.serialise(cert);

function independentCount(input) {
  const n = input.players.length;
  const p = Array.from({ length: n }, () => Array(n).fill(0));
  const o = Array.from({ length: n }, () => Array(n).fill(0));
  const perRound = Array.from({ length: input.rounds.length }, () => Array(n).fill(0));
  for (const row of input.rows) {
    const [round, , ...four] = row;
    for (const player of four) perRound[round][player]++;
    for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) {
      const matrix = (i < 2) === (j < 2) ? p : o;
      matrix[four[i]][four[j]]++;
      matrix[four[j]][four[i]]++;
    }
  }
  const games = Array(n).fill(0);
  const byes = Array(n).fill(0);
  const runs = Array(n).fill(0);
  for (let player = 0; player < n; player++) {
    let run = 0;
    for (let round = 0; round < input.rounds.length; round++) {
      if (perRound[round][player] === 1) { games[player]++; run = 0; }
      else { byes[player]++; run++; runs[player] = Math.max(runs[player], run); }
    }
  }
  const upper = (matrix) => {
    const values = [];
    for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) values.push(matrix[i][j]);
    return values;
  };
  const spread = (values) => Math.max(...values) - Math.min(...values);
  const pValues = upper(p), oValues = upper(o);
  return {
    players: n,
    rounds: input.rounds.length,
    gamesTotal: input.rows.length,
    pairs: n * (n - 1) / 2,
    partnerships: input.rows.length * 2,
    oppositions: input.rows.length * 4,
    appearances: input.rows.length * 4,
    p, o, games, byes, runs,
    pSpread: spread(pValues), oSpread: spread(oValues),
    gamesSpread: spread(games), byeSpread: spread(byes),
  };
}

const independent = independentCount(parsed);

test('the real shared certificate kit loaded', () => {
  assert.equal(typeof C.readback, 'function');
  assert.equal(typeof C.check, 'function');
});
test('the published fixture parses as five named rounds and five games', () => {
  assert.equal(parsed.players.join(','), 'A,B,C,D,E');
  assert.equal(parsed.rounds.join(','), '1,2,3,4,5');
  assert.equal(parsed.rows.length, 5);
});
test('headline player, round and game numbers are independently re-derived', () => {
  assert.deepEqual([independent.players, independent.rounds, independent.gamesTotal], [5, 5, 5]);
  assert.deepEqual([answer.players.length, answer.rounds.length, answer.gameCount], [5, 5, 5]);
});
test('headline partnership, opponent-pair and appearance totals are independently re-derived', () => {
  assert.deepEqual([independent.partnerships, independent.oppositions, independent.appearances], [10, 20, 20]);
  assert.deepEqual([answer.partnerTotal, answer.opponentTotal, answer.games.reduce((a, b) => a + b, 0)], [10, 20, 20]);
});
test('the published partner matrix is independently all ones off the diagonal', () => {
  for (let i = 0; i < 5; i++) for (let j = 0; j < 5; j++) assert.equal(independent.p[i][j], i === j ? 0 : 1);
});
test('the published opponent matrix is independently all twos off the diagonal', () => {
  for (let i = 0; i < 5; i++) for (let j = 0; j < 5; j++) assert.equal(independent.o[i][j], i === j ? 0 : 2);
});
test('games, byes and consecutive-bye runs are independently re-derived', () => {
  assert.deepEqual(independent.games, [4, 4, 4, 4, 4]);
  assert.deepEqual(independent.byes, [1, 1, 1, 1, 1]);
  assert.deepEqual(independent.runs, [1, 1, 1, 1, 1]);
});
test('all four displayed spread headlines and bounds are independently zero', () => {
  assert.deepEqual([independent.pSpread, independent.oSpread, independent.gamesSpread, independent.byeSpread], [0, 0, 0, 0]);
  assert.deepEqual(Object.values(answer.metrics), [0, 0, 0, 0, 0, 0, 0, 0]);
});
test('positive control: the unmodified production checker passes the published fixture', () => {
  const result = C.check(cert);
  assert.equal(result.ok, true, result.lines.filter((line) => !line.ok).map((line) => line.text).join('\n'));
});
test('positive control: the production classification is perfect Whist', () => {
  assert.equal(answer.classification, 'perfect Whist');
  assert.equal(answer.pairDeviations, 'none');
});

const changedFixture = fixture.replace('Round 1: A/E vs D/B', 'Round 1: C/E vs D/B');
const changedParsed = parseSchedule(changedFixture, roster);
const changedAnswer = analyseSchedule(changedParsed, 'perfect-whist');
const changedCert = C.make('doubles-schedule-check', certificateData(changedAnswer));

test('one-player control remains a physically feasible schedule', () => {
  assert.equal(C.check(changedCert).ok, true);
  assert.deepEqual(changedParsed.rows[0], [0, 0, 2, 4, 3, 1]);
});
test('one-player control changes perfect Whist to impossible as claimed', () => {
  assert.equal(changedAnswer.perfect, false);
  assert.equal(changedAnswer.classification, 'impossible as claimed');
});
test('one-player control names exactly the six pair counts it broke', () => {
  assert.equal(changedAnswer.pairDeviations,
    'opponents A/B=1 (want 2); opponents A/D=1 (want 2); partners A/E=0 (want 1); opponents B/C=3 (want 2); opponents C/D=3 (want 2); partners C/E=2 (want 1)');
});

test('null control: a plausible wrong schedule row fails the named partner-matrix assertion', () => {
  const badText = text.replace('schedule[0]: 0 0 0 4 3 1', 'schedule[0]: 0 0 2 4 3 1');
  assert.notEqual(badText, text);
  const result = C.check(C.readback(badText));
  assert.equal(result.ok, false);
  const line = result.lines.find((item) => !item.ok && /partner matrix matches/.test(item.text));
  assert.ok(line);
  assert.match(line.text, /A\/E shown 1, counted 0/);
  assert.match(line.text, /C\/E shown 1, counted 2/);
});
test('truncation control: removing the last matrix row is refused by readback', () => {
  const truncated = text.split('\n').filter((line) => !line.startsWith('partner[4]:')).join('\n');
  assert.throws(() => C.readback(truncated), /partner has 4 row\(s\), the shape row says 5/);
});

function replaceExact(source, before, after) {
  assert.ok(source.includes(before), `fault setup could not find ${JSON.stringify(before)}`);
  const changed = source.replace(before, after);
  assert.notEqual(changed, source);
  return changed;
}

const faults = [
  ['schedule player index', 'schedule[0]: 0 0 0 4 3 1', 'schedule[0]: 0 0 2 4 3 1', /partner matrix matches/],
  ['partner count', 'partner[0]: 0 1 1 1 1', 'partner[0]: 0 1 1 1 0', /partner matrix matches/],
  ['opponent count', 'opponent[0]: 0 2 2 2 2', 'opponent[0]: 0 2 2 2 3', /opponent matrix matches/],
  ['round attendance', 'played_by_round[0]: 1 1 0 1 1', 'played_by_round[0]: 1 1 0 1 0', /round-by-round play/],
  ['games played', 'games: 4 4 4 4 4', 'games: 3 4 4 4 4', /round-by-round play/],
  ['bye count', 'byes: 1 1 1 1 1', 'byes: 2 1 1 1 1', /round-by-round play/],
  ['longest bye run', 'longest_bye_run: 1 1 1 1 1', 'longest_bye_run: 2 1 1 1 1', /longest consecutive-bye/],
  ['pair total', 'pair_count: 10', 'pair_count: 11', /two partnerships and four opponent-pairs/],
  ['partnership total', 'partner_total: 10', 'partner_total: 11', /two partnerships and four opponent-pairs/],
  ['partner spread', 'partner_spread: 0', 'partner_spread: 1', /actual spreads and their arithmetic lower bounds/],
  ['classification', 'classification: perfect Whist', 'classification: balanced', /classification and supplied-claim verdict/],
  ['player label', 'players: A | B | C | D | E', 'players: A | B | C | D | D', /player, round and court labels are nonblank and unambiguous/],
];

for (const [name, before, after, namedLine] of faults) {
  test(`fault table: one doctored ${name} value turns its named assertion red`, () => {
    const badText = replaceExact(text, before, after);
    const rebuilt = C.readback(badText);
    const result = C.check(rebuilt);
    assert.equal(result.ok, false);
    assert.ok(result.lines.some((line) => !line.ok && namedLine.test(line.text)),
      `no red line matched ${namedLine}; red lines were: ${result.lines.filter((line) => !line.ok).map((line) => line.text).join(' | ')}`);
  });
}

test('the control on the controls: unmodified serialised text still passes', () => {
  assert.equal(C.check(C.readback(text)).ok, true);
});
test('CSV input produces the same certificate data as the round text fixture', () => {
  const csv = `round,court,team1player1,team1player2,team2player1,team2player2
1,1,A,E,D,B
2,1,B,C,E,D
3,1,D,A,C,E
4,1,E,B,A,C
5,1,C,D,B,A`;
  const csvAnswer = analyseSchedule(parseSchedule(csv, roster), 'perfect-whist');
  assert.deepEqual(certificateData(csvAnswer), certificateData(answer));
});
test('a player repeated across two courts in one round is refused', () => {
  const bad = `Round 1: A/B vs C/D, A/E vs F/G`;
  assert.throws(() => analyseSchedule(parseSchedule(bad), 'none'), /A appears twice in round 1/);
});
test('a malformed nonblank line is loud and specific', () => {
  assert.throws(() => parseSchedule('Round 1: A/B vs C/D\nthis line vanished'), /line 2: expected/);
});
test('an arithmetic impossibility is stated with the fixed totals', () => {
  const short = analyseSchedule(parseSchedule('Round 1: A/B vs C/D', roster), 'partners-once');
  assert.equal(short.classification, 'impossible as claimed');
  assert.match(short.claimStatus, /2 partnership slots cannot cover 10 pairs exactly once/);
});

// ── the three means the page prints, asserted ─────────────────────────────────────────
// A read-only audit found that the displayed partner, opponent and appearance means were
// computed by the display path and asserted nowhere: the verifier derived the totals and the
// pair count but never their quotients. On the published five-player fixture the exact means
// are 1, 2 and 4, and those three numbers are the whole point of a whist tournament, so they
// are pinned here as exact integers rather than as rounded labels.
test('the three displayed means on the published fixture are exactly 1, 2 and 4', () => {
  const d = C.readback(text).data;
  const players = d.players.length;
  const pairs = (players * (players - 1)) / 2;
  let partnerships = 0, oppositions = 0, appearances = 0;
  for (let i = 0; i < players; i += 1) {
    for (let j = i + 1; j < players; j += 1) {
      partnerships += Number(d.partner[i][j].toString());
      oppositions += Number(d.opponent[i][j].toString());
    }
  }
  for (let i = 0; i < players; i += 1) appearances += Number(d.games[i].toString());
  assert.equal(partnerships / pairs, 1, `partner mean is ${partnerships}/${pairs}`);
  assert.equal(oppositions / pairs, 2, `opponent mean is ${oppositions}/${pairs}`);
  assert.equal(appearances / players, 4, `appearance mean is ${appearances}/${players}`);
  // the control on the control: the divisions must be exact, not merely close
  assert.equal(partnerships % pairs, 0);
  assert.equal(oppositions % pairs, 0);
  assert.equal(appearances % players, 0);
});

// ── the two numbers the page prints about the world, re-derived here ──────────────────
// The page carries two arithmetic exhibits. Both are recomputed from scratch below, because
// a page that prints a number nothing checks is the thing this whole room exists against.

test('the advertised 7-game envelope clears the partner-everyone claim for exactly one player count', () => {
  // 7 games, courts fixed by the vendor's own published mapping (retrieved 2026-08-31):
  // 6-7 -> 1, 8-11 -> 2, 12-15 -> 3, 16-19 -> 4, 20-23 -> 5, 24 -> 6.
  const courtsFor = (n) => (n <= 7 ? 1 : n <= 11 ? 2 : n <= 15 ? 3 : n <= 19 ? 4 : n <= 23 ? 5 : 6);
  const possible = [];
  for (let n = 6; n <= 24; n += 1) {
    const c = courtsFor(n);
    const available = 2 * 7 * c;          // two partnerships per game, seven games, c courts
    const needed = (n * (n - 1)) / 2;     // every pair, once
    if (available >= needed && 4 * c <= n) possible.push(n);
  }
  assert.deepEqual(possible, [8], `the claim is arithmetically possible for ${possible.join(', ')}`);
  // and the four rows the page actually prints
  assert.equal(2 * 7 * 2, 28); assert.equal((8 * 7) / 2, 28);
  assert.equal(2 * 7 * 3, 42); assert.equal((12 * 11) / 2, 66);
  assert.equal(2 * 7 * 6, 84); assert.equal((24 * 23) / 2, 276);
});

test('no court assignment turns the circle construction on 8 players into a whist tournament', () => {
  const n = 8;
  // circle method: player 7 fixed, 0..6 rotate. Produces n-1 rounds of n/2 partnerships.
  const rounds = [];
  for (let r = 0; r < n - 1; r += 1) {
    const pairs = [[n - 1, r]];
    for (let i = 1; i < n / 2; i += 1) {
      pairs.push([(r + i) % (n - 1), ((r - i) % (n - 1) + (n - 1)) % (n - 1)]);
    }
    rounds.push(pairs);
  }
  // it really is partner-perfect, or the rest of this test is about the wrong object
  const seen = new Set();
  for (const rnd of rounds) for (const [a, b] of rnd) seen.add([a, b].sort((x, y) => x - y).join('-'));
  assert.equal(seen.size, (n * (n - 1)) / 2, 'the circle construction should give every pair exactly once');

  const splits = [[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[0, 3], [1, 2]]];
  const key = (a, b) => (a < b ? `${a}-${b}` : `${b}-${a}`);
  let whist = 0, bestSpread = null, tried = 0;
  const total = 3 ** rounds.length;
  for (let code = 0; code < total; code += 1) {
    let c = code;
    const opp = new Map();
    for (const rnd of rounds) {
      const [[i, j], [k, l]] = splits[c % 3]; c = Math.floor(c / 3);
      for (const x of [rnd[i][0], rnd[i][1]]) for (const y of [rnd[j][0], rnd[j][1]]) opp.set(key(x, y), (opp.get(key(x, y)) || 0) + 1);
      for (const x of [rnd[k][0], rnd[k][1]]) for (const y of [rnd[l][0], rnd[l][1]]) opp.set(key(x, y), (opp.get(key(x, y)) || 0) + 1);
    }
    const counts = [];
    for (let a = 0; a < n; a += 1) for (let b = a + 1; b < n; b += 1) counts.push(opp.get(key(a, b)) || 0);
    const lo = Math.min(...counts), hi = Math.max(...counts);
    if (lo === 2 && hi === 2) whist += 1;
    if (!bestSpread || hi - lo < bestSpread[1] - bestSpread[0]) bestSpread = [lo, hi];
    tried += 1;
  }
  assert.equal(tried, 2187, 'all 3^7 court assignments must be tried');
  assert.equal(whist, 0, `${whist} of 2187 court assignments were whist, which contradicts the page`);
  assert.deepEqual(bestSpread, [0, 4], `best reachable opponent spread was ${bestSpread}`);
});

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