"""
europa.io.record
~~~~~~~~~~~~~~~~
Record audio from microphone input.
"""

import numpy as np
from ..core.audio import Audio


def record(
    duration: float,
    sr: int = 44100,
    channels: int = 1,
    device: int = None,
) -> Audio:
    """
    Record audio from the default microphone.

    Args:
        duration : Recording duration in seconds.
        sr       : Sample rate. Default 44100.
        channels : Number of input channels (1=mono, 2=stereo).
        device   : Input device index. None = system default.

    Returns:
        Audio: Recorded audio.

    Examples:
        >>> audio = europa.record(5.0)
        >>> audio = europa.record(10.0, sr=44100, channels=2)
    """
    try:
        import sounddevice as sd
    except ImportError:
        raise ImportError("sounddevice is required for recording. pip install sounddevice")

    print(f"🎙️  Recording {duration}s at {sr} Hz ({channels}ch)...")
    data = sd.rec(
        int(duration * sr),
        samplerate=sr,
        channels=channels,
        dtype=np.float32,
        device=device,
    )
    sd.wait()
    print("✅ Recording done.")

    data = data.T  # (channels, samples)
    if channels == 1:
        data = data[0]

    return Audio(data=data, sr=sr)
