"""AudioMixin — handlers for audio endpoints.

  POST /v1/audio/transcriptions
  POST /v1/audio/speech
"""
from __future__ import annotations

import base64


class AudioMixin:
    """Provides audio endpoint handlers.

    Relies on the concrete class for:
      self._resolve_ctx, self._send_json, self._send_bytes,
      self._not_supported, self._read_body, self._read_raw_body,
      self.headers  (from BaseHTTPRequestHandler).
    """

    def _handle_audio_transcriptions(self) -> None:
        content_type = self.headers.get("Content-Type", "")

        if "application/json" in content_type:
            body = self._read_body()
            if body is None:
                return
            ctx         = self._resolve_ctx(body.get("model"))
            audio_b64   = body.get("audio", "")
            if not audio_b64:
                self._send_json(400, {"error": "'audio' (base64) is required"})
                return
            audio_bytes = base64.b64decode(audio_b64)
            language    = body.get("language")
        else:
            audio_bytes = self._read_raw_body()
            ctx         = self._resolve_ctx(None)
            language    = None

        if ctx.transcribe is None:
            self._not_supported("/v1/audio/transcriptions")
            return

        try:
            text = ctx.transcribe(audio_bytes, language)
        except Exception as exc:  # pylint: disable=broad-except
            self._send_json(500, {"error": str(exc)})
            return

        self._send_json(200, {"text": text})

    def _handle_audio_speech(self) -> None:
        body = self._read_body()
        if body is None:
            return

        ctx = self._resolve_ctx(body.get("model"))
        if ctx.synthesize is None:
            self._not_supported("/v1/audio/speech")
            return

        text = body.get("input", "")
        if not text:
            self._send_json(400, {"error": "'input' is required"})
            return

        voice = body.get("voice")
        speed = float(body.get("speed", 1.0))

        try:
            wav = ctx.synthesize(text, voice, speed)
        except Exception as exc:  # pylint: disable=broad-except
            self._send_json(500, {"error": str(exc)})
            return

        self._send_bytes(200, wav, "audio/wav")
