"""Deepgram Aura-2 TTS implementation using their REST API."""

from __future__ import annotations

import io
import logging

import numpy as np
import soundfile as sf

from roohai.base import TTSModel

logger = logging.getLogger(__name__)

DEEPGRAM_TTS_URL = "https://api.deepgram.com/v1/speak"


class DeepgramTTS(TTSModel):
    META = {
        "display_name": "Deepgram Aura-2",
        "description": "Cloud-based TTS with 90+ natural voices across 7 languages. Requires API key.",
        "kind": "cloud",
        "pip_dependencies": ["httpx"],
        "hf_models": [],
        "estimated_download_mb": 0,
        "config_fields": [
            {
                "name": "api_key",
                "label": "API Key",
                "type": "secret",
                "required": True,
                "env_var": "DEEPGRAM_API_KEY",
                "placeholder": "dg-xxx",
            },
            {
                "name": "model",
                "label": "Voice",
                "type": "select",
                "required": False,
                "default": "aura-2-thalia-en",
                "options": [
                    {"value": "aura-2-thalia-en", "label": "Thalia (F, American, Energetic)"},
                    {"value": "aura-2-apollo-en", "label": "Apollo (M, American, Casual)"},
                    {"value": "aura-2-aurora-en", "label": "Aurora (F, British, Professional)"},
                    {"value": "aura-2-orion-en", "label": "Orion (M, British, Confident)"},
                    {"value": "aura-2-luna-en", "label": "Luna (F, American, Friendly)"},
                    {"value": "aura-2-helios-en", "label": "Helios (M, American, Warm)"},
                    {"value": "aura-2-athena-en", "label": "Athena (F, British, Clear)"},
                    {"value": "aura-2-arcas-en", "label": "Arcas (M, American, Professional)"},
                    {"value": "aura-2-stella-en", "label": "Stella (F, American, Mature)"},
                    {"value": "aura-2-perseus-en", "label": "Perseus (M, American, Confident)"},
                ],
            },
            {
                "name": "sample_rate",
                "label": "Sample Rate",
                "type": "text",
                "required": False,
                "default": "24000",
            },
        ],
    }

    def __init__(
        self,
        api_key: str | None = None,
        model: str = "aura-2-thalia-en",
        sample_rate: int = 24000,
        **kwargs,
    ) -> None:
        self.model = model
        self.sample_rate = int(sample_rate)
        self._api_key = api_key
        self._client = None

    def load(self) -> None:
        import os

        import httpx

        key = self._api_key or os.environ.get("DEEPGRAM_API_KEY")
        if not key:
            raise RuntimeError(
                "Deepgram API key required. Set DEEPGRAM_API_KEY env var or pass api_key in config."
            )
        self._client = httpx.Client(
            headers={
                "Authorization": f"Token {key}",
                "Content-Type": "application/json",
            },
            timeout=30.0,
        )

    def synthesize(self, text: str) -> tuple[np.ndarray, int]:
        if not self.is_loaded:
            raise RuntimeError("Model not loaded. Call load() first.")

        response = self._client.post(
            DEEPGRAM_TTS_URL,
            params={
                "model": self.model,
                "encoding": "linear16",
                "container": "wav",
                "sample_rate": self.sample_rate,
            },
            json={"text": text},
        )
        response.raise_for_status()

        data, sr = sf.read(io.BytesIO(response.content), dtype="float32")
        if data.ndim > 1:
            data = data.mean(axis=1)
        return data, sr

    def unload(self) -> None:
        if self._client is not None:
            self._client.close()
            self._client = None

    @property
    def is_loaded(self) -> bool:
        return self._client is not None
