"""WAV file export functions for backward compatibility.

This module provides the legacy export_wav function that was used in older tests.
The implementation wraps the modern output.wav pipeline handler.
"""

from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

import numpy as np

if TYPE_CHECKING:
    from numpy.typing import NDArray


def export_wav(
    data: NDArray[np.float64],
    path: str | Path,
    sample_rate: int,
    bit_depth: int = 16,
    normalize: bool = True,
) -> None:
    """Export audio data as WAV file.

    Args:
        data: Audio samples (1D array of floats, typically in [-1.0, 1.0] range).
        path: Output WAV file path.
        sample_rate: Sample rate in Hz.
        bit_depth: Bit depth (8, 16, or 32, default: 16).
        normalize: Normalize to full scale (default: True).

    Example:
        >>> import numpy as np
        >>> from oscura.export.legacy.wav import export_wav
        >>> audio = np.sin(2 * np.pi * 440 * np.linspace(0, 1, 48000))
        >>> export_wav(audio, "tone.wav", sample_rate=48000)
    """
    import wave

    import numpy as np

    # Convert to numpy array if needed
    audio_data = np.asarray(data)

    # Normalize if requested
    if normalize:
        max_val = np.abs(audio_data).max()
        if max_val > 0:
            audio_data = audio_data / max_val

    # Convert to integer format based on bit depth
    if bit_depth == 8:
        audio_int = (audio_data * 127 + 128).astype(np.uint8)
    elif bit_depth == 16:
        audio_int = (audio_data * 32767).astype(np.int16)
    elif bit_depth == 32:
        audio_int = (audio_data * 2147483647).astype(np.int32)
    else:
        raise ValueError(f"Unsupported bit depth: {bit_depth}. Must be 8, 16, or 32.")

    # Ensure parent directory exists
    output_path = Path(path).resolve()
    output_path.parent.mkdir(parents=True, exist_ok=True)

    # Write WAV file
    with wave.open(str(output_path), "wb") as wav_file:
        wav_file.setnchannels(1)  # Mono
        wav_file.setsampwidth(bit_depth // 8)
        wav_file.setframerate(sample_rate)
        wav_file.writeframes(audio_int.tobytes())


__all__ = ["export_wav"]
