namespace RecordPlayProbe;

internal static class WavWriter
{
    public static void Write(string path, ReadOnlySpan<short> samples, int sampleRate)
    {
        const short channels = 1;
        const short bitsPerSample = 16;
        const short pcmFormat = 1;

        int byteRate = sampleRate * channels * bitsPerSample / 8;
        short blockAlign = (short)(channels * bitsPerSample / 8);
        int dataBytes = samples.Length * sizeof(short);
        int riffChunkSize = 36 + dataBytes;

        using var fs = new FileStream(path, FileMode.Create, FileAccess.Write);
        using var bw = new BinaryWriter(fs);

        // RIFF header
        bw.Write(new[] { (byte)'R', (byte)'I', (byte)'F', (byte)'F' });
        bw.Write(riffChunkSize);
        bw.Write(new[] { (byte)'W', (byte)'A', (byte)'V', (byte)'E' });

        // fmt chunk
        bw.Write(new[] { (byte)'f', (byte)'m', (byte)'t', (byte)' ' });
        bw.Write(16);              // fmt chunk size for PCM
        bw.Write(pcmFormat);
        bw.Write(channels);
        bw.Write(sampleRate);
        bw.Write(byteRate);
        bw.Write(blockAlign);
        bw.Write(bitsPerSample);

        // data chunk
        bw.Write(new[] { (byte)'d', (byte)'a', (byte)'t', (byte)'a' });
        bw.Write(dataBytes);
        foreach (short s in samples)
            bw.Write(s);
    }
}
