import audioop
import base64
from dataclasses import dataclass


@dataclass(frozen=True)
class McubeAudioSpec:
    # MCube audio format: μ-law at 16kHz for better voice quality
    encoding: str = "audio/x-mulaw"
    sample_rate: int = 16000
    sample_width_bytes: int = 2  # PCM16
    num_channels: int = 1


MCUBE_AUDIO_SPEC = McubeAudioSpec()


def pcm16_to_mulaw(pcm16_bytes: bytes) -> bytes:
    """PCM16 (linear signed int16 LE) -> mulaw bytes."""
    # audioop.lin2ulaw expects width=2 and input as raw int16 PCM.
    return audioop.lin2ulaw(pcm16_bytes, MCUBE_AUDIO_SPEC.sample_width_bytes)


def mulaw_to_pcm16(mulaw_bytes: bytes, *, width_bytes: int = 2) -> bytes:
    """mulaw bytes -> PCM16 (linear signed int16 LE)."""
    return audioop.ulaw2lin(mulaw_bytes, width_bytes)


def to_base64_bytes(raw: bytes) -> str:
    return base64.b64encode(raw).decode("ascii")


def from_base64_str(b64: str) -> bytes:
    return base64.b64decode(b64)

