// WHICH ASSERTION FAILS IF THE ANSWER IS SIMPLY WRONG? Assertions 3 through 14
// independently re-derive every headline number in the published example. Assertions
// 16 and 17 require a one-cent wrong answer to fail on Bob's named envy line. The fault
// table in the final assertions doctors one serialized value at a time and requires the
// real shipped checker to fail on the line naming the affected property.

import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import {
  PUBLISHED_EXAMPLE_TEXT,
  buildBundle,
  parsePaste,
  registerDefinitions,
} from '../../public/tools/rent-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;
registerDefinitions(C);

const fixture = JSON.parse(readFileSync(new URL('./fixtures/peters-procaccia-zhu-2022.json', import.meta.url), 'utf8'));

let passed = 0;
let failed = 0;
let number = 0;

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

function independentSummary(raw) {
  const Q = C.Q;
  const rent = C.parseQ(raw.rent);
  const prices = raw.prices.map(C.parseQ);
  const values = raw.values.map((row) => row.map(C.parseQ));
  const assignment = raw.assignment.map((room) => raw.rooms.indexOf(room));
  const priceTotal = prices.reduce((total, price) => total.add(price), Q(0));
  let enviousPeople = 0;
  let maxEnvy = Q(0);
  for (let person = 0; person < raw.people.length; person += 1) {
    const held = assignment[person];
    const own = values[person][held].sub(prices[held]);
    let personEnvy = Q(0);
    for (let room = 0; room < raw.rooms.length; room += 1) {
      const gap = values[person][room].sub(prices[room]).sub(own);
      if (gap.gt(personEnvy)) personEnvy = gap;
    }
    if (personEnvy.gt(0)) enviousPeople += 1;
    if (personEnvy.gt(maxEnvy)) maxEnvy = personEnvy;
  }
  let chosenValue = Q(0);
  for (let person = 0; person < raw.people.length; person += 1) chosenValue = chosenValue.add(values[person][assignment[person]]);
  const negativePrices = prices.filter((price) => price.lt(0)).length;
  const zeroPrices = prices.filter((price) => price.eq(0)).length;
  const roundedPrices = prices.map((price) => C.parseQ(price.toFixed(2)));
  const roundedTotal = roundedPrices.reduce((total, price) => total.add(price), Q(0));
  let roundedEnviousPeople = 0;
  let maxRoundedEnvy = Q(0);
  for (let person = 0; person < raw.people.length; person += 1) {
    const held = assignment[person];
    const own = values[person][held].sub(roundedPrices[held]);
    let personEnvy = Q(0);
    for (let room = 0; room < raw.rooms.length; room += 1) {
      const gap = values[person][room].sub(roundedPrices[room]).sub(own);
      if (gap.gt(personEnvy)) personEnvy = gap;
    }
    if (personEnvy.gt(0)) roundedEnviousPeople += 1;
    if (personEnvy.gt(maxRoundedEnvy)) maxRoundedEnvy = personEnvy;
  }
  return {
    people: raw.people.length,
    priceTotal,
    priceDelta: priceTotal.sub(rent),
    enviousPeople,
    maxEnvy,
    chosenValue,
    negativePrices,
    zeroPrices,
    roundedTotal,
    roundedDelta: roundedTotal.sub(rent),
    roundedEnviousPeople,
    maxRoundedEnvy,
  };
}

const publishedRaw = fixture.input;
const bundle = buildBundle(publishedRaw, C);
const headline = independentSummary(publishedRaw);

test('the page example text transcribes the research fixture exactly', () => {
  assert.deepEqual(parsePaste(PUBLISHED_EXAMPLE_TEXT), publishedRaw);
});

test('the published worked example passes the unmodified full checker', () => {
  const result = C.check(bundle.fullCertificate);
  assert.equal(result.ok, true);
});

test('headline person count is independently re-derived as 3', () => assert.equal(headline.people, 3));
test('headline price total is independently re-derived as 1000', () => assert.equal(headline.priceTotal.toString(), '1000'));
test('headline rent difference is independently re-derived as 0', () => assert.equal(headline.priceDelta.toString(), '0'));
test('headline envious-person count is independently re-derived as 0', () => assert.equal(headline.enviousPeople, 0));
test('headline maximum exact envy is independently re-derived as 0', () => assert.equal(headline.maxEnvy.toString(), '0'));
test('headline chosen assignment value is independently re-derived as 1600', () => assert.equal(headline.chosenValue.toString(), '1600'));
test('headline negative-price count is independently re-derived as 0', () => assert.equal(headline.negativePrices, 0));
test('headline zero-price count is independently re-derived as 0', () => assert.equal(headline.zeroPrices, 0));
test('headline rounded total is independently re-derived as 1000', () => assert.equal(headline.roundedTotal.toString(), '1000'));
test('headline rounded rent difference is independently re-derived as 0', () => assert.equal(headline.roundedDelta.toString(), '0'));
test('headline rounded envious-person count is independently re-derived as 0', () => assert.equal(headline.roundedEnviousPeople, 0));
test('headline maximum rounded envy is independently re-derived as 0', () => assert.equal(headline.maxRoundedEnvy.toString(), '0'));

test('the published tie is accepted exactly, not treated as envy', () => {
  const bobLine = C.check(bundle.fullCertificate).lines.find((line) => /Bob/.test(line.text));
  assert.equal(bobLine.ok, true);
  assert.match(bobLine.text, /ties count as no envy/);
});

const oneCentWrong = structuredClone(publishedRaw);
oneCentWrong.prices[1] = '500.01';
const oneCentResult = C.check(buildBundle(oneCentWrong, C).fullCertificate);

test('null control: raising Bob\'s assigned price by one cent makes the full checker fail', () => {
  assert.equal(oneCentResult.ok, false);
});

test('null control: the one-cent perturbation fails on Bob\'s named envy line only among envy lines', () => {
  const failedEnvy = oneCentResult.lines.filter((line) => !line.ok && /envies/.test(line.text));
  assert.equal(failedEnvy.length, 1);
  assert.match(failedEnvy[0].text, /^Bob envies Room 1 by exactly 0\.01/);
});

test('the full certificate round-trips through serialized text', () => {
  const rebuilt = C.readback(C.serialise(bundle.fullCertificate));
  assert.equal(C.check(rebuilt).ok, true);
});

test('the paste adapter refuses an extra valuation row instead of ignoring it', () => {
  assert.throws(() => parsePaste(`${PUBLISHED_EXAMPLE_TEXT}\nDana | 1 | 2 | 3`), /Expected 3 valuation rows, found 4/);
});

test('the paste adapter refuses a duplicate valuation row instead of keeping the last one', () => {
  const duplicate = PUBLISHED_EXAMPLE_TEXT.replace('Charlie | 300 | 100 | 600', 'Bob | 300 | 100 | 600');
  assert.throws(() => parsePaste(duplicate), /valuation row for Bob appears twice/);
});

test('truncation control: removing the last valuation row is refused by readback', () => {
  const truncated = C.serialise(bundle.fullCertificate).split('\n').filter((line) => !line.startsWith('value[2]:')).join('\n');
  assert.throws(() => C.readback(truncated), /shape row says 3/);
});

const fractional = {
  rent: '1', people: ['Alice', 'Bob'], rooms: ['Room 1', 'Room 2'],
  values: [['1', '0'], ['0', '1/3']], assignment: ['Room 1', 'Room 2'], prices: ['1/3', '2/3'],
};
const fractionalBundle = buildBundle(fractional, C);

test('an exact fractional split can pass before cent rounding', () => assert.equal(C.check(fractionalBundle.fullCertificate).ok, true));
test('cent rounding is checked afresh and catches Bob\'s exact 1/150 envy', () => {
  const result = C.check(fractionalBundle.roundCertificate);
  assert.equal(result.ok, false);
  assert.ok(result.lines.some((line) => !line.ok && /^Bob envies Room 1 by exactly 1\/150 after cent rounding/.test(line.text)));
});

const negative = buildBundle({
  rent: '0', people: ['A', 'B'], rooms: ['Bad room', 'Good room'],
  values: [['10', '0'], ['0', '10']], assignment: ['Bad room', 'Good room'], prices: ['-1', '1'],
}, C);
test('a valid negative price is flagged without making a good split fail', () => {
  const result = C.check(negative.fullCertificate);
  assert.equal(result.ok, true);
  assert.ok(result.lines.some((line) => line.ok && /negative: Bad room/.test(line.text)));
});

const zero = buildBundle({
  rent: '0', people: ['A', 'B'], rooms: ['Room 1', 'Room 2'],
  values: [['10', '0'], ['0', '10']], assignment: ['Room 1', 'Room 2'], prices: ['0', '0'],
}, C);
test('zero prices are flagged without making a good split fail', () => {
  const result = C.check(zero.fullCertificate);
  assert.equal(result.ok, true);
  assert.ok(result.lines.some((line) => line.ok && /zero: Room 1, Room 2/.test(line.text)));
});

const nonOptimal = buildBundle({
  rent: '0', people: ['A', 'B'], rooms: ['Room 1', 'Room 2'],
  values: [['0', '10'], ['10', '0']], assignment: ['Room 1', 'Room 2'], prices: ['0', '0'],
}, C);
test('a nonoptimal assignment carries a checkable better comparison assignment', () => {
  const result = C.check(nonOptimal.fullCertificate);
  assert.equal(result.ok, false);
  assert.ok(result.lines.some((line) => !line.ok && /comparison assignment has value 20, which beats the chosen value 0/.test(line.text)));
});

const goodText = C.serialise(bundle.fullCertificate);
// Print the comparison row once, so a fixture that drifts is visible rather than mysterious.
const comparisonRow = goodText.split('\n').find((l) => l.startsWith('comparisonAssignment:')) || '';
const faults = [
  { name: 'stated rent', from: 'rent: 1000', to: 'rent: 1001', line: /prices sum to .*not the stated rent/ },
  { name: 'last room price', from: 'price: 100 500 400', to: 'price: 100 500 399', line: /prices sum to .*not the stated rent/ },
  { name: 'duplicate assigned room', from: 'assignment: 0 1 2', to: 'assignment: 0 0 2', line: /assignment does not use each room exactly once/ },
  { name: 'Alice alternative value', from: 'value[0]: 300 400 300', to: 'value[0]: 300 701 300', line: /^Alice envies Room 2/ },
  { name: 'Bob alternative value', from: 'value[1]: 300 700 0', to: 'value[1]: 301 700 0', line: /^Bob envies Room 1/ },
  { name: 'Charlie alternative value', from: 'value[2]: 300 100 600', to: 'value[2]: 301 100 600', line: /^Charlie envies Room 1/ },
  { name: 'person potential', from: 'personPotential: 300 600 600', to: 'personPotential: 299 600 600', line: /potentials do not meet the reported value exactly/ },
  { name: 'room potential', from: 'roomPotential: 0 100 0', to: 'roomPotential: 0 99 0', line: /dual potentials fail to upper-bound/ },
  // The comparison is now the best single two-person swap rather than a copy of the chosen
  // assignment, so this fixture reads 1 0 2. Two faults, because the row now carries two
  // separate properties: that it is a permutation at all, and that it is a DIFFERENT one.
  { name: 'comparison assignment', from: 'comparisonAssignment: 1 0 2', to: 'comparisonAssignment: 1 1 2', line: /comparison assignment is not a valid one-to-one assignment/ },
  { name: 'comparison repeating the chosen assignment', from: 'comparisonAssignment: 1 0 2', to: 'comparisonAssignment: 0 1 2', line: /repeats the chosen assignment/ },
  { name: 'duplicate person label', from: 'people: Alice | Bob | Charlie', to: 'people: Bob | Bob | Charlie', line: /Person and room labels must be present and unique/ },
];

for (const fault of faults) {
  test(`fault table: one changed ${fault.name} fails on its named line`, () => {
    assert.equal(goodText.split(fault.from).length, 2, 'the source value must occur exactly once');
    const doctored = goodText.replace(fault.from, fault.to);
    const result = C.check(C.readback(doctored));
    assert.equal(result.ok, false);
    assert.ok(result.lines.some((line) => !line.ok && fault.line.test(line.text)), `no failed line matched ${fault.line}`);
  });
}

// ── the invariant that can only fail if this page is broken ───────────────────────────
// Under quasi-linear utilities, envy-free rent division is a Walrasian equilibrium with unit
// demand, so the first welfare theorem applies: an envy-free split's assignment ALWAYS
// maximises the total of the reported values (Svensson 1983; Gal, Mash, Procaccia and Zick,
// JACM 2017, Theorem 3.2). The page says so, and says the combination "no envy, but the rooms
// went to the wrong people" cannot occur. That sentence needs a test, or it is decoration.
//
// This brute-forces both sides on random small instances: the envy check comes from the
// engine, the welfare side from enumerating every permutation, and the assertion is that no
// instance is ever envy-free while some other assignment carries more total value. It goes red
// if the envy comparison is ever written the wrong way round, which is the single likeliest
// defect in this file's subject.
function permutations(n) {
  if (n === 1) return [[0]];
  const out = [];
  for (const rest of permutations(n - 1)) {
    for (let i = 0; i <= rest.length; i++) out.push([...rest.slice(0, i), n - 1, ...rest.slice(i)]);
  }
  return out;
}

// A small deterministic generator, so a failure is reproducible from the seed alone.
function lcg(seed) { let x = seed >>> 0; return () => (x = (Math.imul(x, 1664525) + 1013904223) >>> 0) / 4294967296; }

// Prices are swept over a coarse grid rather than drawn at random, because random prices are
// almost never envy-free: the first version of this test drew them and reached its subject only
// 16 times in 240 trials, which its own guard caught. A sweep puts thousands of envy-free cases
// in front of the assertion.
function priceVectors(n, rent, step) {
  const out = [];
  const rec = (left, k, acc) => {
    if (k === 1) { out.push([...acc, left]); return; }
    for (let p = 0; p <= left; p += step) rec(left - p, k - 1, [...acc, p]);
  };
  rec(rent, n, []);
  return out;
}

test('envy-freeness implies the assignment maximises total reported value (swept exhaustively)', () => {
  const rand = lcg(20260831);
  let envyFreeSeen = 0, checked = 0;
  for (let trial = 0; trial < 120; trial++) {
    const n = 2 + (trial % 2); // 2 and 3 people, so the sweep stays exhaustive
    const rent = 600, step = 30;
    const value = [];
    for (let i = 0; i < n; i++) {
      const row = [];
      for (let j = 0; j < n; j++) row.push(Math.round(rand() * 500));
      value.push(row);
    }
    const perms = permutations(n);
    const best = Math.max(...perms.map((alt) => value.reduce((sum, row, i) => sum + row[alt[i]], 0)));
    for (const price of priceVectors(n, rent, step)) {
      for (const seat of perms) {
        checked++;
        const envyFree = value.every((row, i) => row.every((v, j) => (row[seat[i]] - price[seat[i]]) >= (v - price[j])));
        if (!envyFree) continue;
        envyFreeSeen++;
        const chosen = value.reduce((sum, row, i) => sum + row[seat[i]], 0);
        assert.equal(chosen, best, `envy-free at trial ${trial}, prices ${price}, seats ${seat}, but total value ${chosen} < best ${best}`);
      }
    }
  }
  // The control on the control: an assertion that never reaches its subject cannot fail. The
  // first version of this test tripped exactly this guard.
  assert.ok(envyFreeSeen > 200, `only ${envyFreeSeen} envy-free cases in ${checked} candidates, so this test barely ran`);
});

// ── the dual potentials, re-derived rather than merely perturbed ──────────────────────
// A read-only audit found that the printed potential vector was only ever tested by changing
// one entry and watching the shipped checker refuse it. That proves sensitivity. It does not
// establish that the printed vector satisfies the property it claims. Both halves are here:
// the exact vector this example produces, pinned, and the dual conditions recomputed from
// the valuations alone.
test('the printed dual potentials satisfy the dual conditions, re-derived from the values', () => {
  const d = C.readback(goodText).data;
  const n = d.people.length;
  const u = d.personPotential, v = d.roomPotential;
  // feasibility: u_i + v_j >= value(i, j) for every pair
  for (let i = 0; i < n; i += 1) {
    for (let j = 0; j < n; j += 1) {
      assert.ok(u[i].add(v[j]).gte(d.value[i][j]),
        `dual infeasible at (${i},${j}): ${u[i].toString()} + ${v[j].toString()} < ${d.value[i][j].toString()}`);
    }
  }
  // complementary slackness: equality on the chosen pairs
  let chosen = C.Q(0), dual = C.Q(0);
  for (let i = 0; i < n; i += 1) {
    const room = Number(d.assignment[i].toString());
    assert.ok(u[i].add(v[room]).eq(d.value[i][room]), `no equality on the chosen pair for person ${i}`);
    chosen = chosen.add(d.value[i][room]);
    dual = dual.add(u[i]).add(v[i]);
  }
  // and the bound closes, which is what makes it a certificate of optimality
  assert.ok(chosen.eq(dual), `chosen ${chosen.toString()} does not equal the dual total ${dual.toString()}`);
  // the pin, so a change to the printed vector has to be deliberate
  assert.equal(u.map((q) => q.toString()).join(' '), '300 600 600');
  assert.equal(v.map((q) => q.toString()).join(' '), '0 100 0');
});

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