import assert from 'node:assert/strict';
import { assessQuote, verifyReport, REPORT_SCHEMA, SCOPE_KEYS } from '../../public/tools/battery-quote-check/audit.mjs';
import { MODEL_SCHEMA, CERTIFICATE_SCHEMA, UNITS } from '../../public/tools/battery-quote-check/certificate.mjs';

// Hand-derived two-interval witness, independent of the proposal engine.
// p=(.1,.4): interval allowances=0, capacity allowance=.3,
// free initial-state allowance=.1, so U=.4. Empty-start policy saves .3.
const certificate = {
  schema: CERTIFICATE_SCHEMA, units: { ...UNITS },
  model: {
    schema: MODEL_SCHEMA, capacityBasis: 'usable-stored-kwh', boundary: 'free-initial-and-final',
    capacityKwh: '1', chargePowerKw: '2', dischargePowerKw: '2', chargeEfficiency: '1', dischargeEfficiency: '1',
    intervals: [
      { start: '2026-01-01T00:00:00.000Z', durationMinutes: 30, importKwh: '0', exportKwh: '1', buyRate: '0.4', feedInRate: '0.1' },
      { start: '2026-01-01T00:30:00.000Z', durationMinutes: 30, importKwh: '1', exportKwh: '0', buyRate: '0.4', feedInRate: '0.1' },
    ],
  },
  dual: { prices: ['0.1', '0.4'] },
  policy: { name: 'empty-start-chronological-comparison', chargeKwh: ['1', '0'], dischargeKwh: ['0', '1'], stateKwh: ['0', '1', '0'] },
  claims: { upper: '2/5', policyValue: '3/10', gap: '1/10' },
};
const allScope = Object.fromEntries(SCOPE_KEYS.map(key => [key, true]));
const clone = value => structuredClone(value);
let count = 0;
function test(name, fn) { try { fn(); count++; } catch (error) { error.message = `${name}: ${error.message}`; throw error; } }
function report(quote = '0.41', scope = clone(allScope)) {
  const cert = clone(certificate), context = { quote, scope };
  return { schema: REPORT_SCHEMA, certificate: cert, context, verdict: assessQuote(cert, context) };
}
function rejects(name, mutate) {
  test(name, () => { const r = report(); mutate(r); assert.throws(() => verifyReport(r)); });
}

test('Hand-derived ceiling and policy values survive independent report verification', () => {
  const result = verifyReport(report());
  assert.equal(result.summary.upper, '2/5'); assert.equal(result.summary.policyValue, '3/10'); assert.equal(result.summary.gap, '1/10');
  assert.equal(result.verdict.status, 'exceeds');
});
for (const quote of ['0', '0.3999999999999999999999', '2/5', '0.400000']) test(`Quote ${quote} is not ruled out, never declared worthwhile`, () => {
  const result = verifyReport(report(quote)); assert.equal(result.verdict.status, 'not-ruled-out');
});
test('One exact fraction above the ceiling is not rounded into equality', () => {
  assert.equal(verifyReport(report('0.4000000000000000000001')).verdict.status, 'exceeds');
});
for (const quote of [null, '']) test(`No quote ${String(quote)} carries no comparison verdict`, () => {
  assert.equal(verifyReport(report(quote)).verdict.status, 'no-quote');
});
for (const key of SCOPE_KEYS) {
  for (const replacement of [false, null, undefined, 'true', 1]) test(`${key}=${String(replacement)} cannot authorize comparison`, () => {
    const scope = { ...allScope, [key]: replacement };
    assert.equal(verifyReport(report('1000000', scope)).verdict.status, 'not-comparable');
  });
  test(`Missing ${key} cannot authorize comparison`, () => {
    const scope = { ...allScope }; delete scope[key];
    assert.equal(verifyReport(report('1000000', scope)).verdict.status, 'not-comparable');
  });
}
test('Missing scope produces a refusal even with a large quote', () => {
  const r = report(); delete r.context.scope; r.verdict = { status: 'not-comparable', label: 'Assumptions not matched' };
  assert.equal(verifyReport(r).verdict.status, 'not-comparable');
});
test('Missing scope cannot retain an exceeds conclusion', () => {
  const r = report(); delete r.context.scope; assert.throws(() => verifyReport(r));
});
for (const quote of ['-0.1', 'NaN', 'Infinity', '1e3', 100, {}, '1/0']) test(`Invalid quoted saving ${String(quote)} is refused`, () => {
  const r = report(); r.context.quote = quote; assert.throws(() => verifyReport(r));
});

rejects('Wrong report schema', r => { r.schema = 'battery-quote-check-report/v2'; });
rejects('No certificate', r => { delete r.certificate; });
rejects('Missing all exact claims', r => { delete r.certificate.claims; });
rejects('Wrong upper claim', r => { r.certificate.claims.upper = '3/10'; });
rejects('Wrong policy claim', r => { r.certificate.claims.policyValue = '2/5'; });
rejects('Wrong gap claim', r => { r.certificate.claims.gap = '0'; });
rejects('False optimality claim', r => { r.certificate.claims.status = 'interval-model-optimum'; });
rejects('Wrong unit', r => { r.certificate.units.energy = 'DC kWh'; });
rejects('Changed meter value invalidates policy feasibility', r => { r.certificate.model.intervals[1].importKwh = '0.5'; });
rejects('Changed tariff invalidates exact value claims', r => { r.certificate.model.intervals[1].buyRate = '0.5'; });
rejects('Changed capacity invalidates state feasibility', r => { r.certificate.model.capacityKwh = '0.5'; });
rejects('Wrong endpoint declaration', r => { r.certificate.model.boundary = 'empty-start-and-final'; });
rejects('Truncated dual', r => { r.certificate.dual.prices.pop(); });
rejects('Truncated policy', r => { r.certificate.policy.stateKwh.pop(); });
rejects('Out-of-order meter readings', r => { r.certificate.model.intervals.reverse(); });
rejects('Quote changed across the threshold with a stale verdict', r => { r.context.quote = '0.39'; });
rejects('Assumption changed with a stale verdict', r => { r.context.scope.sameAssumptions = false; });
rejects('Status forged from exceeds to not-ruled-out', r => { r.verdict.status = 'not-ruled-out'; });
rejects('Verdict label forged', r => { r.verdict.label = 'Guaranteed profitable'; });
rejects('Verdict missing', r => { delete r.verdict; });
test('No-quote mode still verifies arithmetic instead of accepting a forged bound', () => {
  const r = report(null); r.certificate.claims.upper = '0'; assert.throws(() => verifyReport(r));
});
for (const key of ['upper', 'policyValue', 'gap']) test(`No-quote report still requires the exact ${key} claim`, () => {
  const r = report(null); delete r.certificate.claims[key]; assert.throws(() => verifyReport(r));
});
test('An empty claims object cannot bypass report completeness with no quote', () => {
  const r = report(null); r.certificate.claims = {}; assert.throws(() => verifyReport(r));
});
test('Not-comparable mode still verifies arithmetic', () => {
  const r = report('0.41', {}); r.certificate.claims.policyValue = '100'; assert.throws(() => verifyReport(r));
});

console.log(`Battery Quote Check report: ${count} adversarial and hand-derived checks passed.`);
