from __future__ import annotations

from pathlib import Path

try:
    from openai import OpenAI
except Exception:
    OpenAI = None


LANG_NAMES = {
    "uk": "Ukrainian",
    "en": "English",
    "de": "German",
    "fr": "French",
    "es": "Spanish",
    "pl": "Polish",
}


class OpenAITranslationPipeline:
    def __init__(
        self,
        api_key: str,
        transcription_model: str = "gpt-4o-mini-transcribe",
        translation_model: str = "gpt-4o-mini",
        tts_model: str = "gpt-4o-mini-tts",
        voice: str = "alloy",
    ):
        if OpenAI is None:
            raise RuntimeError("Модуль openai не встановлений. Запустіть INSTALL_DEPENDENCIES.bat.")
        if not api_key.strip():
            raise ValueError("OpenAI API-ключ порожній.")
        self.client = OpenAI(api_key=api_key.strip())
        self.transcription_model = transcription_model
        self.translation_model = translation_model
        self.tts_model = tts_model
        self.voice = voice

    def transcribe(self, audio_path: Path, source_language: str) -> str:
        with audio_path.open("rb") as audio:
            result = self.client.audio.transcriptions.create(
                model=self.transcription_model,
                file=audio,
                language=source_language,
            )
        return (getattr(result, "text", "") or "").strip()

    def translate(self, text: str, source_language: str, target_language: str) -> str:
        source = LANG_NAMES.get(source_language, source_language)
        target = LANG_NAMES.get(target_language, target_language)
        response = self.client.responses.create(
            model=self.translation_model,
            instructions=(
                f"Translate spoken {source} into natural concise spoken {target}. "
                "Return only the translation, no notes."
            ),
            input=text,
        )
        return (response.output_text or "").strip()

    def synthesize(self, text: str, output_path: Path):
        with self.client.audio.speech.with_streaming_response.create(
            model=self.tts_model,
            voice=self.voice,
            input=text,
            response_format="wav",
        ) as response:
            response.stream_to_file(output_path)
