#!/usr/bin/env node
// Tests the shipped engine and its independent certificate checker.
// node research/battery-quote-check/verify-engine.mjs [--performance]
// No files are written. Public path: public/tools/battery-quote-check/.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { performance } from 'node:perf_hooks';
import { buildModel, evaluateModel } from '../../public/tools/battery-quote-check/engine.mjs';
import { verifyCertificate } from '../../public/tools/battery-quote-check/certificate.mjs';
import { formatDecimal } from '../../public/tools/battery-quote-check/rational.mjs';

let passed = 0;
const equal = (a, b, label) => { assert.equal(a, b, label); passed++; };
const truth = (a, label) => { assert.ok(a, label); passed++; };
const rejects = (fn, label) => { assert.throws(fn, undefined, label); passed++; };
const clone = (x) => structuredClone(x);
function input(rows, options = {}) {
  let time = Date.UTC(2026, 0, 1);
  return { capacityKwh: '1', chargePowerKw: '4', dischargePowerKw: '4', chargeEfficiency: '1', dischargeEfficiency: '1',
    tariffs: { buyRate: '0.3', feedInRate: '0.05' },
    intervals: rows.map((r) => { const out = { start: new Date(time).toISOString(), durationMinutes: r.minutes ?? 60,
      exportKwh: String(r.export ?? 0), importKwh: String(r.import ?? 0),
      ...(r.buy !== undefined ? { buyRate: String(r.buy) } : {}), ...(r.feed !== undefined ? { feedInRate: String(r.feed) } : {}) };
    time += out.durationMinutes * 60000; return out; }), ...options };
}

const cases = [
  ['nothing to move', input([{}]), '0', '0'],
  ['free initial stock is allowed in the upper model', input([{ import: 1 }]), '3/10', '0'],
  ['one cycle with opportunity cost', input([{ export: 1 }, { import: 1 }]), '3/10', '1/4'],
  ['two cycles share only one free initial unit', input([{ export: 1 }, { import: 1 }, { export: 1 }, { import: 1 }]), '11/20', '1/2'],
  ['early load cannot use later surplus in the empty-start policy', input([{ import: 1 }, { export: 1 }]), '3/10', '0'],
  ['greedy misses the dearer late load', input([{ export: 1 }, { import: 1, buy: 0.1 }, { import: 1, buy: 0.5 }]), '1/2', '1/20'],
  ['losses on each side', input([{ export: 1.25, feed: 0.08 }, { import: 0.8, buy: 0.5 }],
    { chargeEfficiency: '0.8', dischargeEfficiency: '0.8' }), '2/5', '3/10'],
  ['capacity binds', input([{ export: 2, feed: 0 }, { import: 2, buy: 1 }]), '1', '1'],
  ['negative feed-in is valuable at a free terminal state', input([{ export: 1, feed: -0.1 }]), '1/10', '1/10'],
  ['negative buy does not force discharge', input([{ import: 1, buy: -0.1 }]), '0', '0'],
  ['zero capacity with separated channels', input([{ export: 1, feed: 0 }, { import: 1, buy: 1 }], { capacityKwh: '0' }), '0', '0'],
  ['zero-capacity simultaneous interval is only a relaxation', input([{ export: 1, import: 1, feed: 0, buy: 1 }], { capacityKwh: '0' }), '1', '0'],
  ['power multiplied by duration', input([{ export: 4, minutes: 30 }, { import: 3, minutes: 15 }, { import: 3, minutes: 15 }],
    { capacityKwh: '2', chargePowerKw: '1', dischargePowerKw: '1' }), '3/20', '1/8'],
];
const bundles = cases.map(([name, source, upper, lower]) => ({ name, source, upper, lower, bundle: evaluateModel(buildModel(source)) }));
const precisionBundle = evaluateModel(buildModel(input([{ export: 1, minutes: 5, feed: 0 }, { import: 1, minutes: 5, buy: 0.4 }],
  { chargePowerKw: '0.000000001', dischargePowerKw: '1', chargeEfficiency: '0.999999999' })));

function behavior(check, evaluate = evaluateModel, record = false) {
  let count = 0;
  const is = (a, b, label) => { assert.equal(a, b, label); count++; };
  const no = (fn, label) => { assert.throws(fn, undefined, label); count++; };
  for (const f of bundles) {
    const bundle = evaluate(buildModel(f.source));
    is(bundle.summary.upper, f.upper, `${f.name}: sharp hand-derived upper`);
    is(bundle.summary.policyValue, f.lower, `${f.name}: comparison value`);
    const r = check(bundle.certificate);
    is(r.upper, f.upper, `${f.name}: separate checker agrees`);
    is(r.policyValue, f.lower, `${f.name}: separate checker verifies policy`);
  }
  const base = bundles.find((f) => f.name === 'one cycle with opportunity cost').bundle.certificate;
  const attacks = [
    ['false upper', (c) => { c.claims.upper = '0'; }],
    ['false lower', (c) => { c.claims.policyValue = '100'; }],
    ['false gap', (c) => { c.claims.gap = '0'; }],
    ['false optimal label', (c) => { c.claims.status = 'interval-model-optimum'; }],
    ['missing dual', (c) => { c.dual.prices.pop(); }],
    ['infinite dual', (c) => { c.dual.prices[0] = 'Infinity'; }],
    ['numeric input', (c) => { c.model.capacityKwh = 1; }],
    ['wrong capacity basis', (c) => { c.model.capacityBasis = 'unspecified'; }],
    ['wrong boundary', (c) => { c.model.boundary = 'starts-empty'; }],
    ['wrong unit', (c) => { c.units.energy = 'kW'; }],
    ['negative charge', (c) => { c.policy.chargeKwh[0] = '-1'; }],
    ['negative discharge', (c) => { c.policy.dischargeKwh[0] = '-1'; }],
    ['state conservation', (c) => { c.policy.stateKwh[1] = '1/2'; }],
    ['storage capacity', (c) => { c.model.capacityKwh = '1/2'; }],
    ['charge power', (c) => { c.model.chargePowerKw = '1/2'; }],
    ['discharge power', (c) => { c.model.dischargePowerKw = '1/2'; delete c.claims; c.dual.prices = ['1', '1']; }],
    ['export cap', (c) => { c.model.intervals[0].exportKwh = '1/2'; }],
    ['import cap', (c) => { c.model.intervals[1].importKwh = '1/2'; delete c.claims; c.dual.prices = ['1', '1']; }],
    ['zero efficiency', (c) => { c.model.chargeEfficiency = '0'; }],
    ['efficiency above one', (c) => { c.model.dischargeEfficiency = '1.1'; }],
    ['gap in data', (c) => { c.model.intervals[1].start = '2026-01-01T02:00:00Z'; }],
    ['overlap in data', (c) => { c.model.intervals[1].start = c.model.intervals[0].start; }],
    ['ambiguous local timestamp', (c) => { c.model.intervals[0].start = '2026-01-01T00:00:00'; }],
    ['rolled invalid date', (c) => { c.model.intervals[0].start = '2026-02-30T00:00:00Z'; }],
    ['unsupported period', (c) => { c.model.intervals[0].durationMinutes = 20; }],
    ['prime-denominator model', (c) => { c.model.intervals[0].exportKwh = '1/7'; }],
    ['prime-denominator dual', (c) => { c.dual.prices[0] = '1/7'; }],
    ['precision overflow', (c) => { c.model.intervals[0].exportKwh = '0.0000000001'; }],
  ];
  for (const [name, attack] of attacks) { const c = clone(base); attack(c); no(() => check(c), name); }
  const stolen = clone(base); delete stolen.claims;
  stolen.policy.chargeKwh = ['0', '0']; stolen.policy.stateKwh = ['1', '1', '0']; stolen.dual.prices = ['1', '1'];
  no(() => check(stolen), 'initial policy guard is necessary even with a loose dual');
  const loose = clone(base); delete loose.claims; loose.dual.prices = ['1', '1'];
  is(check(loose).upper, '39/20', 'arbitrary supported loose prices remain valid');
  const terminal = clone(bundles.find((f) => f.name === 'negative feed-in is valuable at a free terminal state').bundle.certificate);
  is(check(terminal).policyFinalKwh, '1', 'terminal inventory is permitted');
  const lossyDual = clone(bundles.find((f) => f.name === 'losses on each side').bundle.certificate);
  delete lossyDual.claims; lossyDual.dual.prices = ['1/10', '2/5'];
  is(check(lossyDual).upper, '2/5', 'nonzero dual prices independently exercise discharge efficiency');
  is(check(precisionBundle.certificate).valid, true, 'nine-digit power and efficiency retain the full five-minute denominator');
  if (record) passed += count;
  return count;
}
behavior(verifyCertificate, evaluateModel, true);

// Independent integer-SOC oracle, including arbitrary initial AND final stock.
// Integer tariff, energy and lossless fixtures keep all oracle arithmetic integer.
function oracle(C, rows) {
  let values = Array(C + 1).fill(0);
  for (const r of rows) {
    const next = Array(C + 1).fill(-Infinity);
    for (let before = 0; before <= C; before++) for (let c = 0; c <= r.export; c++) for (let d = 0; d <= r.import; d++) {
      const after = before + c - d;
      if (after >= 0 && after <= C) next[after] = Math.max(next[after], values[before] + r.buy * d - r.feed * c);
    }
    values = next;
  }
  return Math.max(...values);
}
let seed = 0x871aec19;
const random = (n) => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) % n; };
let dualChecks = 0;
for (let k = 0; k < 60; k++) {
  const C = random(4), rows = Array.from({ length: 3 }, () => ({ export: random(3), import: random(3), buy: random(4) - 1, feed: random(4) - 1 }));
  const m = buildModel(input(rows, { capacityKwh: String(C) })), expected = oracle(C, rows), b = evaluateModel(m);
  equal(Number(b.summary.upper), expected, `tiny model ${k}: proposed bound meets independent exhaustive optimum`);
  truth(Number(b.summary.policyValue.includes('/') ? NaN : b.summary.policyValue) <= expected, `tiny model ${k}: policy does not exceed independent optimum`);
  for (const p0 of [-1, 0, 1, 2]) for (const p1 of [-1, 0, 1, 2]) for (const p2 of [-1, 0, 1, 2]) {
    const c = { ...b.certificate, dual: { prices: [p0, p1, p2].map(String) } }; delete c.claims;
    truth(Number(verifyCertificate(c).upper) >= expected, `tiny model ${k}: each independently checked dual bounds all schedules`); dualChecks++;
  }
}

const denseRates = Array.from({ length: 200 }, (_, k) => ({ export: k % 2 ? 0 : 1, import: k % 2 ? 1 : 0,
  buy: (1000 + k) / 1000, feed: k / 1000 }));
const sampled = evaluateModel(buildModel(input(denseRates)), { maxPriceStates: 16 });
equal(sampled.summary.candidateCount, 16, 'price lattice is capped');
truth(sampled.summary.fullCandidateCount > 16 && sampled.summary.restrictedPriceSearch, 'sampling is disclosed');
truth(verifyCertificate(sampled.certificate).valid, 'sampled prices are certified exactly');
const coarse = evaluateModel(buildModel(input([{ export: 1 }, { import: 1 }])), { maxPriceStates: 1 });
truth(verifyCertificate(coarse.certificate).valid, 'even one price state remains an honest bound');
equal(formatDecimal('1/3', 2, 'up'), '0.34', 'ceiling rounds outward');
equal(formatDecimal('-1/3', 2, 'up'), '-0.33', 'upward rounding handles negatives');
equal(formatDecimal('-1/3', 2, 'down'), '-0.34', 'downward rounding handles negatives');
equal(formatDecimal('9007199254740993', 2), '9007199254740993.00', 'formatting does not lose large integer precision');

// Mutate the checker in memory. Relative imports are rewritten to the actual
// shipped rational module; no files are patched and every mutant must import.
const checkerURL = new URL('../../public/tools/battery-quote-check/certificate.mjs', import.meta.url);
const rationalURL = new URL('../../public/tools/battery-quote-check/rational.mjs', import.meta.url);
const source = readFileSync(checkerURL, 'utf8').replace("'./rational.mjs'", JSON.stringify(rationalURL.href));
const mutations = [
  ['omit initial term', 'initialAllowance = mul(C, positive(firstPrice))', 'initialAllowance = ZERO'],
  ['omit terminal term', 'terminalAllowance = mul(C, positive(neg(previousPrice)))', 'terminalAllowance = ZERO'],
  ['reverse capacity difference', 'positive(sub(p, previousPrice))', 'positive(sub(previousPrice, p))'],
  ['wrong discharge loss in state', 'div(d, ed)', 'mul(d, ed)'],
  ['wrong discharge loss in bound', 'div(p, ed)', 'mul(p, ed)'],
  ['skip conservation', 'equal(next, add(state, sub(mul(ec, c), div(d, ed))), `State conservation at interval ${t + 1}`);', '/* no balance */'],
  ['skip initial comparison guard', "equal(state, ZERO, 'The comparison policy must start empty');", '/* no endpoint */'],
  ['skip charge limit', 'range(c, ZERO, r.cmax, `Policy charge ${t + 1}`);', '/* no charge box */'],
  ['skip discharge limit', 'range(d, ZERO, r.dmax, `Policy discharge ${t + 1}`);', '/* no discharge box */'],
  ['skip capacity limit', 'range(next, ZERO, C, `Policy state ${t + 1}`);', '/* no capacity box */'],
  ['lose five-minute denominator factor', '12n * PRECISION * PRECISION * ed.n', '3n * PRECISION * PRECISION * ed.n'],
];
const mutationResults = [];
for (const [name, from, to] of mutations) {
  equal(source.split(from).length - 1, 1, `${name}: one real mutation site`);
  const mod = await import('data:text/javascript;base64,' + Buffer.from(source.replace(from, to)).toString('base64'));
  let caught = false; try { behavior(mod.verifyCertificate); } catch { caught = true; }
  truth(caught, `${name}: behavioral detection`); mutationResults.push({ name, caught });
}

const performanceResults = [];
if (process.argv.includes('--performance')) for (const n of [17520, 105120]) {
  const minutes = n === 17520 ? 30 : 5;
  const rows = Array.from({ length: n }, (_, k) => ({ minutes, import: k % 12 < 6 ? 0.2 : 0, export: k % 12 < 6 ? 0 : 0.3,
    buy: k % 48 < 36 ? 0.25 : 0.45, feed: 0.06 }));
  const started = performance.now();
  const m = buildModel(input(rows, { capacityKwh: '10', chargePowerKw: '5', dischargePowerKw: '5', chargeEfficiency: '0.9' }));
  const built = performance.now(), b = evaluateModel(m), solved = performance.now();
  const v = verifyCertificate(b.certificate), checked = performance.now();
  equal(v.upper, b.summary.upper, `${n} intervals: independent recheck`);
  performanceResults.push({ intervals: n, buildMs: Math.round(built - started), evaluateAndCheckMs: Math.round(solved - built),
    recheckMs: Math.round(checked - solved), candidateCount: b.summary.candidateCount,
    certificateBytes: Buffer.byteLength(JSON.stringify(b.certificate)) });
}
console.log(JSON.stringify({ passed, namedCases: cases.length, tinyModels: 60, dualChecks, mutations: mutationResults,
  ...(performanceResults.length ? { syntheticPerformance: performanceResults } : {}) }, null, 2));
