# wcs/ai/ElevenLabsTTSClient.py
"""
ElevenLabs TTS API client for Millionaire game.

Supports eleven_flash_v2_5 (low latency) and eleven_v3 (expressive with audio tags).
"""

import xbmcaddon
import xbmc
import xbmcvfs
import requests
from wcs.ai.DialogAIDebugRequest import show_api_request_debug

ADDON = xbmcaddon.Addon()

ELEVENLABS_API_KEY = 'sk_759aea75ff43f641554f3892f4554c23f45204c638480b67'
ELEVENLABS_API_URL = 'https://api.elevenlabs.io/v1/text-to-speech'
TTS_OUTPUT_PATH = xbmcvfs.translatePath('special://temp/tts_milionar_el.mp3')

# Voice ID mapping: setting value -> ElevenLabs voice_id
VOICE_MAP = {
    'Adam': 'pNInz6obpgDQGcFmaJgB',
    'Rachel': '21m00Tcm4TlvDq8ikWAM',
    'Antoni': 'ErXwobaYiN019PkySvjV',
    'Josh': 'TxGEqnHWrfWFTfGW9XjX',
    'Charlotte': 'XB0fDUnXU5powFXDhCwa',
    'Aria': '9BWtsMINqrJLrRacOk9x',
}

DEFAULT_VOICE = 'Adam'
DEFAULT_MODEL = 'eleven_flash_v2_5'

# Voice settings per model
VOICE_SETTINGS = {
    'eleven_flash_v2_5': {
        'stability': 0.5,
        'similarity_boost': 0.75,
        'style': 0.0,
        'use_speaker_boost': True,
    },
    'eleven_v3': {
        'stability': 0.0,
        'similarity_boost': 0.75,
        'style': 0.0,
        'use_speaker_boost': True,
    },
}


class ElevenLabsTTSException(Exception):
    pass


def generate_tts(text, voice_name=DEFAULT_VOICE, model_id=DEFAULT_MODEL):
    """
    Generate TTS audio file using ElevenLabs API.

    :param text: Text to speak (str)
    :param voice_name: Voice name from VOICE_MAP (str)
    :param model_id: ElevenLabs model ID (str)
    :return: Path to audio file (str)
    :raises: ElevenLabsTTSException on error
    """
    voice_id = VOICE_MAP.get(voice_name, VOICE_MAP[DEFAULT_VOICE])
    voice_settings = VOICE_SETTINGS.get(model_id, VOICE_SETTINGS[DEFAULT_MODEL])

    url = '{}/{}'.format(ELEVENLABS_API_URL, voice_id)

    headers = {
        'xi-api-key': ELEVENLABS_API_KEY,
        'Content-Type': 'application/json',
        'Accept': 'audio/mpeg',
    }

    data = {
        'text': text,
        'model_id': model_id,
        'voice_settings': voice_settings,
    }

    # Debug dialog
    if not show_api_request_debug("ElevenLabs TTS", model_id, data):
        raise ElevenLabsTTSException(
            'Odeslání TTS požadavku bylo zrušeno uživatelem.'
        )

    try:
        response = requests.post(url, headers=headers, json=data, timeout=30)
        if response.status_code != 200:
            raise ElevenLabsTTSException(
                'Chyba ElevenLabs TTS API: {} {}'.format(
                    response.status_code, response.text
                )
            )
        f = xbmcvfs.File(TTS_OUTPUT_PATH, 'w+b')
        f.write(response.content)
        f.close()
        return TTS_OUTPUT_PATH
    except ElevenLabsTTSException:
        raise
    except Exception as e:
        raise ElevenLabsTTSException(
            'Chyba při generování TTS: {}'.format(e)
        )
