#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

function writeAscii(buffer, offset, text) {
  buffer.write(text, offset, text.length, 'ascii');
}

function createWav(file, durationSeconds) {
  const sampleRate = 16000;
  const channels = 1;
  const bitsPerSample = 16;
  const samples = Math.max(1, Math.floor(durationSeconds * sampleRate));
  const dataSize = samples * channels * (bitsPerSample / 8);
  const buffer = Buffer.alloc(44 + dataSize);

  writeAscii(buffer, 0, 'RIFF');
  buffer.writeUInt32LE(36 + dataSize, 4);
  writeAscii(buffer, 8, 'WAVE');
  writeAscii(buffer, 12, 'fmt ');
  buffer.writeUInt32LE(16, 16);
  buffer.writeUInt16LE(1, 20);
  buffer.writeUInt16LE(channels, 22);
  buffer.writeUInt32LE(sampleRate, 24);
  buffer.writeUInt32LE(sampleRate * channels * (bitsPerSample / 8), 28);
  buffer.writeUInt16LE(channels * (bitsPerSample / 8), 32);
  buffer.writeUInt16LE(bitsPerSample, 34);
  writeAscii(buffer, 36, 'data');
  buffer.writeUInt32LE(dataSize, 40);

  for (let i = 0; i < samples; i++) {
    const t = i / sampleRate;
    const pulse = Math.sin(2 * Math.PI * 220 * t) * 0.12;
    const beat = Math.sin(2 * Math.PI * 1.2 * t) > 0.96 ? 0.08 : 0;
    const value = Math.max(-1, Math.min(1, pulse + beat));
    buffer.writeInt16LE(Math.round(value * 32767), 44 + i * 2);
  }

  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, buffer);
}

const out = process.argv[2] || 'examples/minimal/input/demo_voice.wav';
const duration = Number(process.argv[3] || 22);

if (!Number.isFinite(duration) || duration <= 0) {
  console.error('Duration must be a positive number.');
  process.exit(1);
}

createWav(path.resolve(out), duration);
console.log(`Created ${out} (${duration}s placeholder WAV)`);
