"""Opt-in TTS using GPT-4o Mini TTS (interview prompts stay text by default)."""

from __future__ import annotations

from app.schemas.common import JobStatus
from app.schemas.tts import TtsSynthesizeRequest, TtsSynthesizeResponse
from app.services.voice.tts_openai import TtsError, audio_to_base64, synthesize_speech
from app.services.voice.voice_store import voice_profile_store


class TtsService:
    async def synthesize(self, payload: TtsSynthesizeRequest) -> TtsSynthesizeResponse:
        voice_param: str | dict[str, str] | None = payload.voice
        used_voice_id = payload.voice_id

        if payload.voice_id:
            profile = voice_profile_store.get(payload.voice_id)
            if profile is None:
                return TtsSynthesizeResponse(
                    correlation_id=payload.correlation_id,
                    interview_id=payload.interview_id,
                    status=JobStatus.FAILED,
                    stub=False,
                    message=f"Unknown voice_id: {payload.voice_id}",
                    error_code="voice_not_found",
                    voice_id=payload.voice_id,
                )
            voice_param = profile.speech_voice_param()

        try:
            result = await synthesize_speech(
                text=payload.text,
                voice=voice_param,
                instructions=payload.instructions,
                response_format=payload.response_format,
                language=payload.language,
            )
        except TtsError as exc:
            return TtsSynthesizeResponse(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id,
                status=JobStatus.FAILED,
                stub=False,
                message=str(exc),
                error_code=exc.code,
                voice_id=used_voice_id,
            )

        return TtsSynthesizeResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message=result.message,
            model=result.model,
            voice=result.voice if isinstance(result.voice, (str, dict)) else str(result.voice),
            voice_id=used_voice_id,
            audio_base64=audio_to_base64(result.audio_bytes),
            audio_mime_type=result.mime_type,
            format=result.format,
        )
