// Reproduce the reader's offline workflow from the public ZIP, using Node only.
// This imports no repository checker or optimizer: the child runs extracted files.
import assert from 'node:assert/strict';
import { readFileSync, writeFileSync, mkdtempSync, rmSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';

const base = new URL('../../public/tools/battery-quote-check/', import.meta.url);
const modules = ['check-report.mjs', 'audit.mjs', 'certificate.mjs', 'rational.mjs'];
const expectedNames = [...modules, 'README.txt'];
const archive = readFileSync(new URL('checker.zip', base));
const exampleBytes = readFileSync(new URL('example-report.json', base));

// Table-based CRC is independent of the packager's per-bit implementation.
const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
  for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
  return value >>> 0;
});
function crc32(bytes) {
  let value = 0xffffffff;
  for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
  return (value ^ 0xffffffff) >>> 0;
}

function extractStoredZip(bytes) {
  assert.ok(bytes.length >= 22, 'ZIP must contain an end-of-directory record');
  const end = bytes.length - 22;
  assert.equal(bytes.readUInt32LE(end), 0x06054b50, 'No trailing bytes or archive comment are expected');
  assert.equal(bytes.readUInt16LE(end + 4), 0, 'ZIP must not span disks');
  assert.equal(bytes.readUInt16LE(end + 6), 0, 'Directory must be on the same disk');
  const count = bytes.readUInt16LE(end + 10);
  assert.equal(count, expectedNames.length, 'Bundle must contain exactly four modules and README');
  assert.equal(bytes.readUInt16LE(end + 8), count, 'Disk entry count must match total count');
  assert.equal(bytes.readUInt16LE(end + 20), 0, 'Archive comment must be empty');
  const directorySize = bytes.readUInt32LE(end + 12), directoryStart = bytes.readUInt32LE(end + 16);
  assert.equal(directoryStart + directorySize, end, 'Central directory must end exactly at the end record');
  const entries = new Map();
  let central = directoryStart, nextLocal = 0;
  for (let index = 0; index < count; index++) {
    assert.ok(central + 46 <= end, 'Central entry header must fit inside the directory');
    assert.equal(bytes.readUInt32LE(central), 0x02014b50, 'Expected central directory entry');
    assert.equal(bytes.readUInt16LE(central + 4), 20, 'Expected simple ZIP version 2.0 creator');
    assert.equal(bytes.readUInt16LE(central + 6), 20, 'Expected ZIP version 2.0 reader requirement');
    assert.equal(bytes.readUInt16LE(central + 8), 0, 'Encryption, data descriptors and other flags are not allowed');
    assert.equal(bytes.readUInt16LE(central + 10), 0, 'Only the ZIP store method is used');
    assert.equal(bytes.readUInt16LE(central + 12), 0, 'Expected deterministic midnight timestamp');
    assert.equal(bytes.readUInt16LE(central + 14), 33, 'Expected deterministic 1980-01-01 DOS date');
    const crc = bytes.readUInt32LE(central + 16), size = bytes.readUInt32LE(central + 20);
    assert.equal(bytes.readUInt32LE(central + 24), size, 'Stored compressed and uncompressed sizes must match');
    const nameLength = bytes.readUInt16LE(central + 28);
    assert.equal(bytes.readUInt16LE(central + 30), 0, 'Unexpected central extra field');
    assert.equal(bytes.readUInt16LE(central + 32), 0, 'Unexpected entry comment');
    assert.equal(bytes.readUInt16LE(central + 34), 0, 'Entry must begin on disk zero');
    assert.equal(bytes.readUInt16LE(central + 36), 0, 'Unexpected internal attributes');
    assert.equal(bytes.readUInt32LE(central + 38), 0, 'No directory or symlink attributes are allowed');
    assert.ok(central + 46 + nameLength <= end, 'Filename must fit inside the directory');
    const nameBytes = bytes.subarray(central + 46, central + 46 + nameLength);
    assert.ok(nameBytes.every(byte => byte >= 0x20 && byte < 0x7f), 'Filenames must be plain ASCII');
    const name = nameBytes.toString('ascii');
    assert.ok(expectedNames.includes(name) && /^[A-Za-z0-9-]+\.(?:mjs|txt)$/.test(name), 'Only safe allowlisted flat filenames may be extracted');
    assert.ok(!entries.has(name), `Duplicate ZIP entry: ${name}`);
    const local = bytes.readUInt32LE(central + 42);
    assert.equal(local, nextLocal, 'Local entries must be contiguous, without hidden records or preamble');
    assert.ok(local + 30 <= directoryStart, 'Local header must precede the directory');
    assert.equal(bytes.readUInt32LE(local), 0x04034b50, 'Expected local file header');
    assert.equal(bytes.readUInt16LE(local + 4), 20, 'Local ZIP version must match');
    assert.equal(bytes.readUInt16LE(local + 6), 0, 'Local flags must match');
    assert.equal(bytes.readUInt16LE(local + 8), 0, 'Local method must be store');
    assert.equal(bytes.readUInt16LE(local + 10), 0, 'Local deterministic time must match');
    assert.equal(bytes.readUInt16LE(local + 12), 33, 'Local deterministic date must match');
    assert.equal(bytes.readUInt32LE(local + 14), crc, 'Local CRC must match directory CRC');
    assert.equal(bytes.readUInt32LE(local + 18), size, 'Local compressed size must match');
    assert.equal(bytes.readUInt32LE(local + 22), size, 'Local uncompressed size must match');
    assert.equal(bytes.readUInt16LE(local + 26), nameLength, 'Local filename length must match');
    assert.equal(bytes.readUInt16LE(local + 28), 0, 'Unexpected local extra field');
    assert.ok(bytes.subarray(local + 30, local + 30 + nameLength).equals(nameBytes), 'Local filename bytes must match central filename bytes');
    const dataStart = local + 30 + nameLength, dataEnd = dataStart + size;
    assert.ok(dataEnd <= directoryStart, 'File data must not overlap the central directory');
    const data = bytes.subarray(dataStart, dataEnd);
    assert.equal(crc32(data), crc, `CRC mismatch for ${name}`);
    entries.set(name, data);
    nextLocal = dataEnd; central += 46 + nameLength;
  }
  assert.equal(nextLocal, directoryStart, 'No unlisted local entry or hidden bytes may precede the directory');
  assert.equal(central, end, 'No unlisted central entry may remain');
  assert.deepEqual([...entries.keys()].sort(), [...expectedNames].sort(), 'Bundle filename set must be exact');
  return entries;
}

const entries = extractStoredZip(archive);
for (const name of modules) assert.ok(entries.get(name).equals(readFileSync(new URL(name, base))), `${name} in checker.zip is stale or differs from the current public source`);
const readme = entries.get('README.txt').toString('utf8');
assert.match(readme, /^BATTERY QUOTE CHECK: independent exact verifier\n/);
assert.match(readme, /Node\.js 20 or later/);
assert.match(readme, /node check-report\.mjs battery-report\.json/);
assert.match(readme, /No npm install, account, server or network is needed\./);
assert.match(readme, /does not authenticate readings, equipment, quote, scope confirmations or hashes/);

const example = JSON.parse(exampleBytes.toString('utf8'));
assert.equal(example.schema, 'battery-quote-check-report/v1');
assert.equal(example.context.synthetic, true, 'Public example must disclose that it is invented');
assert.equal(example.context.currency, 'AUD');
assert.match(example.context.description, /Invented.*not a real household or quote/i);
assert.deepEqual(Object.keys(example.context.scope).sort(), ['existingSolar', 'completeMeter', 'sameAssumptions', 'excludedServices'].sort());
assert.ok(Object.values(example.context.scope).every(value => value === true), 'Example must make its conditional scope explicit');
assert.equal(example.certificate.model.intervals.length, 2, 'Reader example should remain inspectable by hand');
assert.equal(example.certificate.claims.upper, '2/5', 'Known example exact ceiling is 0.4 AUD');
assert.equal(example.verdict.status, 'exceeds');

const temporary = mkdtempSync(join(tmpdir(), 'battery-checker-reader-'));
function runChecker(filename) {
  const child = spawnSync(process.execPath, ['check-report.mjs', filename], {
    cwd: temporary, encoding: 'utf8', timeout: 20000, maxBuffer: 1024 * 1024,
    env: { ...process.env, NODE_OPTIONS: '', NODE_PATH: '' },
  });
  if (child.error) throw child.error; // Preserve EPERM so the runner can request normal escalation.
  assert.equal(child.signal, null, 'Extracted checker must complete without a timeout or signal');
  return child;
}
try {
  for (const [name, data] of entries) writeFileSync(join(temporary, name), data, { flag: 'wx' });
  writeFileSync(join(temporary, 'example-report.json'), exampleBytes, { flag: 'wx' });
  assert.deepEqual(readdirSync(temporary).sort(), [...expectedNames, 'example-report.json'].sort(), 'Offline directory must contain only bundled files and the public example');
  const good = runChecker('example-report.json');
  assert.equal(good.status, 0, `Extracted checker rejected the public example: ${good.stderr}`);
  assert.equal(good.stderr, '', 'Successful check should not emit an error');
  const checked = JSON.parse(good.stdout);
  assert.match(checked.result, /^PASS:/);
  assert.equal(checked.upperExact, '2/5');
  assert.equal(checked.upperRoundedUp, '0.40');
  assert.equal(checked.comparisonPolicyExact, '3/10');
  assert.equal(checked.verdict.status, 'exceeds');
  assert.match(checked.limit, /Does not authenticate/);

  const tampered = structuredClone(example);
  tampered.certificate.claims.upper = '3/10';
  writeFileSync(join(temporary, 'tampered-report.json'), JSON.stringify(tampered), { flag: 'wx' });
  const bad = runChecker('tampered-report.json');
  assert.equal(bad.status, 1, 'Extracted checker must fail a tampered upper-bound claim');
  assert.equal(bad.stdout, '', 'Failed check must not print a PASS result');
  assert.match(bad.stderr, /^FAIL: Claim upper:/);
  console.log('Battery Quote Check bundle: 5 safe ZIP entries and current module bytes verified; extracted offline reader PASS at exact 2/5 AUD (0.40), tampered claim FAIL.');
} finally {
  rmSync(temporary, { recursive: true, force: true });
}
