"""
Audio utility functions.

Helper functions for audio processing and format conversion.
"""

import struct


def create_wav_header(
    sample_rate: int = 24000,
    channels: int = 1,
    bits_per_sample: int = 16,
    data_size: int = 0
) -> bytes:
    """
    Create a WAV file header.
    
    Args:
        sample_rate: Sample rate in Hz (default: 24000)
        channels: Number of channels (1=mono, 2=stereo)
        bits_per_sample: Bits per sample (usually 16)
        data_size: Size of audio data in bytes (0 for unknown)
    
    Returns:
        WAV header bytes (44 bytes)
    """
    byte_rate = sample_rate * channels * bits_per_sample // 8
    block_align = channels * bits_per_sample // 8
    
    header = struct.pack(
        '<4sI4s4sIHHIIHH4sI',
        b'RIFF',
        36 + data_size,  # File size - 8
        b'WAVE',
        b'fmt ',
        16,  # fmt chunk size
        1,   # PCM format
        channels,
        sample_rate,
        byte_rate,
        block_align,
        bits_per_sample,
        b'data',
        data_size
    )
    
    return header


def add_wav_header(audio_bytes: bytes, sample_rate: int = 24000) -> bytes:
    """
    Add WAV header to raw PCM audio bytes.
    
    Args:
        audio_bytes: Raw PCM audio data (16-bit, mono)
        sample_rate: Sample rate in Hz
    
    Returns:
        Complete WAV file bytes (header + data)
    """
    header = create_wav_header(
        sample_rate=sample_rate,
        channels=1,
        bits_per_sample=16,
        data_size=len(audio_bytes)
    )
    return header + audio_bytes

