import os
import logging
from pathlib import Path
import numpy as np
import soundfile as sf

logger = logging.getLogger(__name__)

def save_audio(
    wav: np.ndarray,
    sample_rate: int,
    output_file: str,
) -> None:
    """Save synthesized audio to WAV, OGG (Vorbis/Opus), or MP3.

    The output format is inferred from the file extension.

    Args:
        wav: Audio waveform array (float32 or float64)
        sample_rate: Sample rate in Hz
        output_path: Path where to save the audio file
    """


    output_path = Path(output_file)
    ext = output_path.suffix.lower()

    output_path.parent.mkdir(parents=True, exist_ok=True)

    if not os.access(output_path.parent, os.W_OK):
        raise PermissionError(
            f"No write permission for directory: {output_path.parent}"
        )


    data = wav.squeeze()

    if ext == ".wav":
        fmt = "WAV"
        subtype = "PCM_16"

    elif ext == ".ogg":
        ogg_subtypes = sf.available_subtypes("OGG")
        if "VORBIS" not in ogg_subtypes:
            raise RuntimeError("OGG supported but no Vorbis subtype available")
        fmt = "OGG"
        subtype = "VORBIS"

    elif ext == ".mp3":
        fmt = "MP3"
        subtype = "MPEG_LAYER_III"

    else:
        raise ValueError(f"Unsupported output format: {ext}")

    BLOCK = 16384
    channels = 1 if data.ndim == 1 else data.shape[1]

    with sf.SoundFile(
        file=str(output_path),
        mode="w",
        samplerate=sample_rate,
        channels=channels,
        format=fmt,
        subtype=subtype,
    ) as f:
        for i in range(0, len(data), BLOCK):
            f.write(data[i:i + BLOCK])



