// Production report builder/reader tests; the separate Python suite checks
// these reports with independent Fraction arithmetic, including every day.
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { buildReport, verifyReport, parseReport, canonical, digest, DECLARATIONS, MAX_REPORT_BYTES } from '../../public/tools/offset-ledger/report.mjs';
import { makeDemo } from '../../public/tools/offset-ledger/demo.mjs';

let checks = 0;
const rejected = [];
const check = (condition, name) => { assert.ok(condition, name); checks++; };
const context = (source = 'synthetic', value = true) => ({ source, inputKind: 'daily-snapshots', declarations: Object.fromEntries(DECLARATIONS.map(key => [key, value])) });
const clone = value => structuredClone(value);
async function reject(name, operation) {
  await assert.rejects(async () => operation(), undefined, name);
  checks++; rejected.push(name);
}
async function seal(report) {
  const { sha256, ...body } = report;
  report.sha256 = await digest(body);
  return report;
}

const example = await buildReport(makeDemo(), context());
check(example.interpretation.status === 'synthetic-example', 'Demo remains synthetic.');
check(example.result.daily.length === 30, 'Demo contains every daily calculation.');
const { sha256, ...body } = example;
check(createHash('sha256').update(canonical(body)).digest('hex') === sha256, 'Independent Node SHA-256 agrees.');
check(canonical(await verifyReport(parseReport(JSON.stringify(example)))) === canonical(example), 'Strict reader roundtrip preserves report.');
check(canonical({ z: 1, a: { b: 2, a: 1 } }) === '{"a":{"a":1,"b":2},"z":1}', 'Canonical keys sort recursively.');
check(canonical([2, 1]) === '[2,1]', 'Canonical arrays preserve order.');

for (const [name, edit, reseal = true] of [
  ['input changed without digest', r => { r.input.rows[0].loan = '1'; }, false],
  ['source changed without digest', r => { r.context.source = 'user'; }, false],
  ['input changed and resealed', r => { r.input.rows[0].loan = '1'; }],
  ['daily fraction changed and resealed', r => { r.result.daily[0].exactCents.withOffset.numerator = '999'; }],
  ['daily rounded value changed and resealed', r => { r.result.daily[0].halfUpCents.withOffset = '999'; }],
  ['daily evidence omitted', r => { r.result.daily.pop(); }],
  ['daily evidence reordered', r => { r.result.daily.reverse(); }],
  ['candidate omitted', r => { r.result.candidates.pop(); }],
  ['model denominator changed', r => { r.result.model.annualDayDivisor = 366; }],
  ['matching bit changed', r => { r.result.candidates[0].compatible = !r.result.candidates[0].compatible; }],
  ['source with stale interpretation', r => { r.context.source = 'user'; }],
  ['declaration with stale interpretation', r => { r.context.declarations.completePeriod = false; }],
  ['expanded scope', r => { r.interpretation.scope = 'bank-authenticity'; }],
  ['unsupported status', r => { r.interpretation.status = 'refund-due'; }],
  ['extra result field', r => { r.result.certified = true; }],
  ['extra report field', r => { r.bankCertified = true; }],
  ['missing report field', r => { delete r.context; }],
  ['unknown version', r => { r.version = 2; }],
  ['boolean version', r => { r.version = true; }],
  ['changed format', r => { r.format = 'bank-report'; }],
  ['upper-case digest', r => { r.sha256 = r.sha256.toUpperCase(); }, false],
  ['integer compatibility bit', r => { r.result.candidates[0].compatible = 1; }],
]) {
  const altered = clone(example); edit(altered);
  if (reseal) await seal(altered);
  await reject(name, () => verifyReport(altered));
}

for (const [name, edit] of [
  ['unsupported source', (i, c) => { c.source = 'certified'; }],
  ['transaction ledger unsupported', (i, c) => { c.inputKind = 'transaction-ledger'; }],
  ['nonboolean declaration', (i, c) => { c.declarations.modelAccepted = 1; }],
  ['missing declaration', (i, c) => { delete c.declarations.modelAccepted; }],
  ['extra declaration', (i, c) => { c.declarations.authenticated = true; }],
  ['empty rows', i => { i.rows = []; }],
  ['row coverage gap', i => { i.rows.pop(); }],
  ['duplicate daily date', i => { i.rows[1].date = i.rows[0].date; }],
  ['invalid calendar date', i => { i.rows[0].date = '2026-09-31'; }],
  ['year zero', i => { i.start = '0000-01-01'; }],
  ['short year', i => { i.start = '26-09-01'; }],
  ['reversed period', i => { i.end = '2026-08-31'; }],
  ['period over 3660 days', i => { i.end = '2040-01-01'; }],
  ['too many rows', i => { i.rows = Array(3661).fill(i.rows[0]); }],
  ['unknown input field', i => { i.interestDayDivisor = 366; }],
  ['missing input field', i => { delete i.observedCharge; }],
  ['fractional observed cent', i => { i.observedCharge = '0.001'; }],
  ['unknown convention', i => { i.conventions = ['bank-default']; }],
  ['duplicate convention', i => { i.conventions = ['daily-half-up', 'daily-half-up']; }],
  ['empty conventions', i => { i.conventions = []; }],
  ['sparse row array', i => { delete i.rows[0]; }],
  ['row array with extra field', i => { i.rows.certified = true; }],
  ['row with symbol field', i => { i.rows[0][Symbol('hidden')] = true; }],
  ['nonenumerable input field', i => { Object.defineProperty(i, 'hidden', { value: true }); }],
  ['foreign object prototype', i => { Object.setPrototypeOf(i.rows[0], { hidden: true }); }],
  ['cyclic input', i => { i.rows[0].loan = i; }],
]) {
  const request = makeDemo(), source = context(); edit(request, source);
  await reject(name, () => buildReport(request, source));
}
for (const field of ['loan', 'offset', 'annualRatePercent']) {
  for (const value of ['-1', '1e3', 'NaN', '.1', '1.', ' 1', '1,000', '1'.repeat(33), '0.' + '1'.repeat(13), 1, null, false]) {
    const request = makeDemo(); request.rows[0][field] = value;
    await reject(`Invalid ${field}: ${String(value)}`, () => buildReport(request, context()));
  }
}
let getterRead = false;
const withGetter = makeDemo();
Object.defineProperty(withGetter.rows[0], 'loan', { enumerable: true, get() { getterRead = true; return '1'; } });
await reject('Getter cannot execute during validation', () => buildReport(withGetter, context()));
check(!getterRead, 'Validation does not execute the getter.');

for (const [name, text] of [
  ['duplicate JSON keys', '{"a":1,"a":2}'],
  ['escaped duplicate JSON keys', '{"a":1,"\\u0061":2}'],
  ['JSON float', '{"version":1.0}'],
  ['JSON exponent', '{"version":1e0}'],
  ['JSON NaN', '{"version":NaN}'],
  ['JSON Infinity', '{"version":Infinity}'],
  ['JSON null', '{"version":null}'],
  ['JSON plus number', '{"version":+1}'],
  ['JSON leading zero', '{"version":01}'],
  ['JSON integer over limit', '{"version":1000000000}'],
  ['JSON number overflow', '{"version":' + '9'.repeat(400) + '}'],
  ['trailing JSON comma', '{"version":1,}'],
  ['trailing array comma', '[1,]'],
  ['trailing content', '{}{}'],
  ['unterminated string', '{"a":"abc}'],
  ['invalid escape', '{"a":"\\q"}'],
  ['unescaped control character', '{"a":"\n"}'],
  ['non-ASCII string', '{"a":"é"}'],
  ['non-ASCII escaped string', '{"a":"\\u200b"}'],
  ['string over limit', JSON.stringify('a'.repeat(513))],
  ['key over limit', JSON.stringify({ ['a'.repeat(65)]: true })],
  ['nesting over limit', '['.repeat(34) + 'true' + ']'.repeat(34)],
  ['tree node limit', '[' + Array(300000).fill('true').join(',') + ']'],
  ['file byte limit', ' '.repeat(MAX_REPORT_BYTES + 1)],
  ['byte-order mark', '\ufeff{}'],
]) await reject(name, () => parseReport(text));
const prototypeKey = parseReport('{"__proto__":{"polluted":true}}');
check(Object.getPrototypeOf(prototypeKey) === null && Object.hasOwn(prototypeKey, '__proto__') && !({}).polluted, 'JSON keys cannot modify prototypes.');

for (const key of DECLARATIONS) {
  const source = context('user'); source.declarations[key] = false;
  const report = await buildReport(makeDemo(), source);
  check(report.interpretation.status === 'insufficient-evidence', `Declaration gates interpretation: ${key}`);
}
const replacement = await buildReport(makeDemo(), context('user'));
check((await verifyReport(replacement)).context.source === 'user', 'Self-consistent replacement is accepted, not authenticated.');
const request = makeDemo(), source = context();
const detached = await buildReport(request, source);
request.rows[0].loan = '1'; source.source = 'user';
check(detached.input.rows[0].loan === '100000' && detached.context.source === 'synthetic', 'Built report is detached from caller inputs.');

console.log(JSON.stringify({ status: 'pass', checks, malformedOrAlteredRejected: rejected.length, scope: 'Synthetic report handling; independent arithmetic covered by verify-report.py.' }, null, 2));
