from __future__ import annotations

from io import BytesIO


class VoiceTranscriber:
    def transcribe(self, audio_bytes: bytes, filename: str = "voice.ogg") -> str:
        raise NotImplementedError


class NullVoiceTranscriber(VoiceTranscriber):
    def transcribe(self, audio_bytes: bytes, filename: str = "voice.ogg") -> str:
        raise RuntimeError("Voice transcription is not configured.")


class OpenAIVoiceTranscriber(VoiceTranscriber):
    def __init__(self, api_key: str, model: str, language: str = "zh") -> None:
        from openai import OpenAI

        self.client = OpenAI(api_key=api_key)
        self.model = model
        self.language = language

    def transcribe(self, audio_bytes: bytes, filename: str = "voice.ogg") -> str:
        audio_file = BytesIO(audio_bytes)
        audio_file.name = filename
        transcript = self.client.audio.transcriptions.create(
            model=self.model,
            file=audio_file,
            response_format="text",
            language=self.language,
        )
        text = getattr(transcript, "text", transcript)
        result = str(text).strip()
        if not result:
            raise RuntimeError("Empty transcription result.")
        return result
