"""OpenAI GPT-4o Mini TTS — speech synthesis."""

from __future__ import annotations

import base64
import logging
from dataclasses import dataclass
from typing import Any

import httpx

from app.config import get_settings

logger = logging.getLogger(__name__)

BUILTIN_VOICES = frozenset(
    {
        "alloy",
        "ash",
        "ballad",
        "coral",
        "echo",
        "fable",
        "onyx",
        "nova",
        "sage",
        "shimmer",
        "verse",
        "marin",
        "cedar",
    }
)


class TtsError(Exception):
    def __init__(self, message: str, *, code: str = "tts_error") -> None:
        self.code = code
        super().__init__(message)


@dataclass
class TtsResult:
    audio_bytes: bytes
    model: str
    voice: str | dict[str, str]
    mime_type: str
    format: str
    stub: bool = False
    message: str = "OK"


async def synthesize_speech(
    *,
    text: str,
    voice: str | dict[str, str] | None = None,
    instructions: str | None = None,
    response_format: str = "mp3",
    language: str | None = None,
) -> TtsResult:
    """Call OpenAI /v1/audio/speech with gpt-4o-mini-tts (or configured model)."""
    settings = get_settings()
    api_key = (settings.openai_api_key or "").strip()
    if not api_key:
        raise TtsError("OPENAI_API_KEY not configured for TTS", code="tts_not_configured")

    model = (settings.tts_model or "gpt-4o-mini-tts").strip()
    fmt = (response_format or settings.tts_default_format or "mp3").lower()
    if fmt not in {"mp3", "wav", "opus", "aac", "flac", "pcm"}:
        fmt = "mp3"

    voice_param: Any
    if isinstance(voice, dict) and voice.get("id"):
        voice_param = {"id": str(voice["id"])}
        voice_label = f"custom:{voice['id']}"
    elif isinstance(voice, str) and voice.strip():
        v = voice.strip()
        if v.lower() in BUILTIN_VOICES:
            voice_param = v.lower()
            voice_label = voice_param
        elif v.startswith("voice_"):
            voice_param = {"id": v}
            voice_label = f"custom:{v}"
        else:
            voice_param = (settings.tts_default_voice or "coral").lower()
            voice_label = voice_param
    else:
        voice_param = (settings.tts_default_voice or "coral").lower()
        voice_label = voice_param

    payload: dict[str, Any] = {
        "model": model,
        "input": text,
        "voice": voice_param,
        "response_format": fmt,
    }
    if instructions:
        payload["instructions"] = instructions
    if language:
        payload["language"] = language

    try:
        async with httpx.AsyncClient(timeout=120.0) as client:
            res = await client.post(
                "https://api.openai.com/v1/audio/speech",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json=payload,
            )
            if res.status_code >= 400:
                raise TtsError(
                    f"TTS HTTP {res.status_code}: {res.text[:400]}",
                    code="tts_provider_failed",
                )
            audio = res.content
    except TtsError:
        raise
    except Exception as exc:  # noqa: BLE001
        raise TtsError(f"TTS failed: {exc}", code="tts_provider_failed") from exc

    if not audio:
        raise TtsError("TTS returned empty audio", code="empty_audio")

    mime = {
        "mp3": "audio/mpeg",
        "wav": "audio/wav",
        "opus": "audio/opus",
        "aac": "audio/aac",
        "flac": "audio/flac",
        "pcm": "audio/pcm",
    }.get(fmt, "application/octet-stream")

    return TtsResult(
        audio_bytes=audio,
        model=model,
        voice=voice_param if isinstance(voice_param, dict) else voice_label,
        mime_type=mime,
        format=fmt,
        message=f"Synthesized via OpenAI {model}",
    )


def audio_to_base64(audio: bytes) -> str:
    return base64.b64encode(audio).decode("ascii")
