#!/usr/bin/env node
// Reproduce the published illustration from the supplied fixed speech WAVs.
// node generate.mjs         node generate.mjs --check (read-only verification)
import { readFile, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';

const rate = 22050;
const gainDb = 6;
const thresholdDb = -25;
const ratio = 4;
const releaseSeconds = 0.15;
const check = process.argv.includes('--check');
const amp = db => 10 ** (db / 20);
const db = amplitude => 20 * Math.log10(amplitude);
const round = value => Number(value.toFixed(6));
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const peak = samples => samples.reduce((max, x) => Math.max(max, Math.abs(x)), 0);
const rms = samples => Math.sqrt(samples.reduce((sum, x) => sum + x * x, 0) / samples.length);

function readWav(bytes) {
  assert.equal(bytes.toString('ascii', 0, 4), 'RIFF');
  assert.equal(bytes.toString('ascii', 8, 12), 'WAVE');
  let format, data;
  for (let offset = 12; offset + 8 <= bytes.length;) {
    const name = bytes.toString('ascii', offset, offset + 4);
    const size = bytes.readUInt32LE(offset + 4);
    assert.ok(offset + 8 + size <= bytes.length, 'Complete WAV chunk');
    const chunk = bytes.subarray(offset + 8, offset + 8 + size);
    if (name === 'fmt ') format = chunk;
    if (name === 'data') data = chunk;
    offset += 8 + size + (size % 2);
  }
  assert.ok(format && data, 'PCM format and data');
  assert.equal(format.readUInt16LE(0), 1, 'PCM');
  assert.equal(format.readUInt16LE(2), 1, 'Mono');
  assert.equal(format.readUInt32LE(4), rate);
  assert.equal(format.readUInt16LE(14), 16);
  return Float64Array.from({ length: data.length / 2 }, (_, i) => data.readInt16LE(i * 2) / 32768);
}

function wav(samples) {
  const bytes = Buffer.alloc(44 + samples.length * 2);
  bytes.write('RIFF', 0); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8);
  bytes.writeUInt32LE(16, 16); bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(1, 22);
  bytes.writeUInt32LE(rate, 24); bytes.writeUInt32LE(rate * 2, 28);
  bytes.writeUInt16LE(2, 32); bytes.writeUInt16LE(16, 34); bytes.write('data', 36);
  bytes.writeUInt32LE(samples.length * 2, 40);
  samples.forEach((x, i) => {
    assert.ok(Number.isFinite(x) && Math.abs(x) < 1, 'Finite, unclipped output');
    bytes.writeInt16LE(Math.round(x * 32768), 44 + i * 2);
  });
  return bytes;
}

// Illustrative full-band peak compressor, not Hearably's product DSP.
// Instant attack, exponential peak-envelope release, hard knee, no look-ahead.
// Above threshold, output dB = threshold + (envelope dB - threshold) / ratio.
function compress(input) {
  const decay = Math.exp(-1 / (rate * releaseSeconds));
  let envelope = 0;
  return input.map(x => {
    envelope = Math.max(Math.abs(x), envelope * decay);
    const reductionDb = Math.max(0, db(envelope) - thresholdDb) * (1 - 1 / ratio);
    return x * amp(-reductionDb);
  });
}

// Independent known-level checks: unity below threshold and a 4:1 transfer
// above it. A down-step must release, rather than retain attenuation forever.
for (const level of [-40, -25, -21, -9]) {
  const input = Float64Array.from({ length: rate }, () => amp(level));
  const expected = level <= thresholdDb ? level : thresholdDb + (level - thresholdDb) / ratio;
  assert.ok(Math.abs(db(compress(input)[rate - 1]) - expected) < 1e-9);
}
const step = Float64Array.from({ length: rate * 2 }, (_, i) => amp(i < rate / 2 ? -9 : -40));
const released = compress(step);
assert.ok(released[rate / 2] < step[rate / 2], 'Release retains attenuation immediately after down-step');
assert.ok(Math.abs(released.at(-1) - step.at(-1)) < 1e-12, 'Release restores unity after settling');

const provenance = JSON.parse(await readFile(new URL('./provenance.json', import.meta.url)));
const locales = {};
for (const locale of ['en', 'de']) {
  const voiceBytes = await readFile(new URL(`./voice-${locale}.wav`, import.meta.url));
  assert.equal(hash(voiceBytes), provenance.voices[locale].sourceSha256, 'Fixed speech source');
  const voice = readWav(voiceBytes);
  const speechStart = Math.round(rate * 0.25);
  const speechEnd = speechStart + voice.length;
  const chimeStart = speechEnd + Math.round(rate * 0.5);
  const chimeEnd = chimeStart + Math.round(rate * 0.8);
  const source = new Float64Array(chimeEnd + Math.round(rate * 0.25));
  const voiceScale = amp(-27) / peak(voice);
  source.set(voice.map(x => x * voiceScale), speechStart);
  const chime = Float64Array.from({ length: chimeEnd - chimeStart }, (_, i) => {
    const t = i / rate;
    const envelope = Math.min(t / 0.02, 1, (0.8 - t) / 0.09);
    return envelope * (Math.sin(2 * Math.PI * 660 * t) + 0.35 * Math.sin(2 * Math.PI * 990 * t));
  });
  const chimeScale = amp(-15) / peak(chime);
  source.set(chime.map(x => x * chimeScale), chimeStart);
  // Process the same quantized original that visitors download.
  const original = readWav(wav(source));
  const variants = [
    ['original', original],
    ['gain', original.map(x => x * amp(gainDb))],
    ['compressed', compress(original).map(x => x * amp(gainDb))],
  ];
  const files = [];
  for (const [id, samples] of variants) {
    const file = `${locale}-${id}.wav`;
    const bytes = wav(samples);
    const decoded = readWav(bytes);
    const speechRmsDbfs = db(rms(decoded.subarray(speechStart, speechEnd)));
    const chimeRmsDbfs = db(rms(decoded.subarray(chimeStart, chimeEnd)));
    files.push({ id, file, sha256: hash(bytes), bytes: bytes.length,
      speechRmsDbfs: round(speechRmsDbfs), chimeRmsDbfs: round(chimeRmsDbfs),
      levelGapDb: round(chimeRmsDbfs - speechRmsDbfs), samplePeakDbfs: round(db(peak(decoded))) });
    const path = new URL(file, import.meta.url);
    if (check) assert.deepEqual(await readFile(path), bytes, `Published file matches: ${file}`);
    else await writeFile(path, bytes);
  }
  for (const metric of ['speechRmsDbfs', 'chimeRmsDbfs']) {
    assert.ok(Math.abs(files[1][metric] - files[0][metric] - gainDb) < 0.005, `Uniform +6 dB: ${locale} ${metric}`);
  }
  assert.ok(Math.abs(files[1].levelGapDb - files[0].levelGapDb) < 0.005, 'Gain preserves level gap');
  assert.equal(files[2].speechRmsDbfs, files[1].speechRmsDbfs, 'Speech remains below threshold; same +6 dB');
  assert.ok(files[1].levelGapDb - files[2].levelGapDb > 7, 'Compressor reduces this sequential level gap');
  assert.ok(files.every(file => file.samplePeakDbfs < -8.9), 'All example sample peaks below -8.9 dBFS');
  locales[locale] = { durationSeconds: round(source.length / rate),
    speechWindowSeconds: [round(speechStart / rate), round(speechEnd / rate)],
    chimeWindowSeconds: [round(chimeStart / rate), round(chimeEnd / rate)], files };
}
const measurements = { version: 1, sampleRate: rate, bitsPerSample: 16, channels: 1,
  settings: { speechPeakDbfs: -27, chimePeakDbfs: -15, gainDb, thresholdDb, ratio, attackSeconds: 0, releaseSeconds, kneeDb: 0, makeupGainDb: gainDb },
  metric: 'RMS over the complete labeled speech and chime windows, including speech pauses; dBFS. Gap is chime RMS minus speech RMS, not an intelligibility score or a LUFS/true-peak measurement.',
  locales };
const serialized = JSON.stringify(measurements, null, 2) + '\n';
const path = new URL('./measurements.json', import.meta.url);
if (check) assert.equal(await readFile(path, 'utf8'), serialized, 'Published measurements match decoded PCM');
else await writeFile(path, serialized);
console.log(`Dialogue example ${check ? 'verified' : 'generated'}: six WAVs, two fixed sources, gain/ratio/release/level-gap checks passed.`);
