"""
europa.core.save
~~~~~~~~~~~~~~~~
Save Audio objects to disk in various formats.
"""

from pathlib import Path
from typing import Union
from .audio import Audio


_FORMAT_SUBTYPES = {
    ".wav":  ("WAV",  "PCM_16"),
    ".flac": ("FLAC", "PCM_24"),
    ".ogg":  ("OGG",  "VORBIS"),
    ".aiff": ("AIFF", "PCM_16"),
    ".au":   ("AU",   "PCM_16"),
}


def save(
    audio: Audio,
    path: Union[str, Path],
    format: str = None,
    subtype: str = None,
) -> None:
    """
    Save an Audio object to disk.

    Args:
        audio   : Audio object to save.
        path    : Destination file path.
        format  : File format string (e.g. 'WAV', 'FLAC'). Auto-detected from extension.
        subtype : Sample format (e.g. 'PCM_16', 'PCM_24', 'FLOAT'). Auto-detected.

    Supported formats: WAV, FLAC, OGG, AIFF, AU

    Examples:
        >>> europa.save(audio, "output.wav")
        >>> europa.save(audio, "output.flac")
        >>> europa.save(audio, "output.ogg")
    """
    try:
        import soundfile as sf
    except ImportError:
        raise ImportError("soundfile is required. Install: pip install soundfile")

    import numpy as np

    path = Path(path)
    ext = path.suffix.lower()

    if format is None or subtype is None:
        fmt, sub = _FORMAT_SUBTYPES.get(ext, ("WAV", "PCM_16"))
        format  = format  or fmt
        subtype = subtype or sub

    data = audio.data
    # soundfile expects (samples, channels)
    if data.ndim == 2:
        data = data.T
    else:
        data = data  # 1D is fine for mono

    sf.write(str(path), data, audio.sr, format=format, subtype=subtype)
