"""
europa.io.playback
~~~~~~~~~~~~~~~~~~
Audio playback via sounddevice.
"""

import numpy as np
import threading
from typing import Optional
from ..core.audio import Audio

_current_stream = None
_lock = threading.Lock()


def play(audio: Audio, blocking: bool = False) -> None:
    """
    Play an Audio object through the default output device.

    Args:
        audio    : Audio object to play.
        blocking : If True, block until playback finishes.

    Examples:
        >>> europa.play(audio)
        >>> europa.play(audio, blocking=True)
    """
    try:
        import sounddevice as sd
    except ImportError:
        raise ImportError("sounddevice is required for playback. pip install sounddevice")

    global _current_stream
    stop()  # stop any existing stream

    data = audio.data
    if data.ndim == 1:
        data = data.reshape(-1, 1)
    else:
        data = data.T  # (samples, channels)

    with _lock:
        _current_stream = sd.play(data, samplerate=audio.sr)

    if blocking:
        sd.wait()


def stop() -> None:
    """Stop all currently playing audio."""
    try:
        import sounddevice as sd
        sd.stop()
    except ImportError:
        pass


def pause() -> None:
    """Pause playback (platform-dependent via sounddevice stream)."""
    # sounddevice doesn't natively support pause; stop is the safe approach
    stop()


def resume() -> None:
    """Resume is not supported directly; use play() again."""
    raise NotImplementedError(
        "sounddevice does not support resume. Call play() again."
    )
