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

ADDON = xbmcaddon.Addon()

OPENAI_API_KEY = ADDON.getSetting('openai_api_key')
TTS_MODEL_DEFAULT = 'gpt-4o-mini-tts-2025-03-20'
TTS_OUTPUT_PATH = xbmcvfs.translatePath('special://temp/tts_milionar.wav')
TTS_API_URL = 'https://api.openai.com/v1/audio/speech'

VOICE_DEFAULT = 'alloy'
INSTRUCTIONS_DEFAULT = (
    'Energetic, dramatic delivery. Build suspense with pauses before reveals. '
    'Sound like a charismatic TV quiz show host keeping the audience engaged.'
)

class OpenAITTSException(Exception):
    pass

def generate_tts(question_text, voice=VOICE_DEFAULT, style=None, instructions=None, language='cz'):
    """
    Vygeneruje TTS audio soubor s otázkou pomocí OpenAI API.
    :param question_text: Text otázky (str)
    :param voice: Název hlasu (str)
    :param style: IGNORED (kept for backward compat, uses moderator_styles)
    :param instructions: (volitelně) přímo instrukce pro hlas (str)
    :param language: Jazyk (str, default 'cz')
    :return: Cesta k audio souboru (str)
    :raises: OpenAITTSException při chybě
    """
    if not OPENAI_API_KEY:
        raise OpenAITTSException('Chybí OpenAI API klíč v nastavení doplňku.')

    # Load TTS instructions from moderator style SKILL.md
    prompt = INSTRUCTIONS_DEFAULT
    if instructions:
        prompt = instructions
    else:
        try:
            from wcs.games.moderator_styles import get_tts_instructions
            prompt = get_tts_instructions()
        except Exception:
            pass

    # Load model from settings, fallback to default
    tts_model = ADDON.getSetting('milionar_tts_model') or TTS_MODEL_DEFAULT

    headers = {
        'Authorization': f'Bearer {OPENAI_API_KEY}',
        'Content-Type': 'application/json'
    }
    data = {
        'model': tts_model,
        'input': question_text,
        'voice': voice,
        'instructions': prompt,
        'response_format': 'wav'
    }
    # Debug dialog před odesláním
    if not show_api_request_debug("OpenAI TTS", tts_model, data):
        raise OpenAITTSException('Odeslání TTS požadavku bylo zrušeno uživatelem.')
    try:
        response = requests.post(TTS_API_URL, headers=headers, json=data, timeout=30)
        if response.status_code != 200:
            raise OpenAITTSException(f'Chyba OpenAI TTS API: {response.status_code} {response.text}')
        # Ukládej přes xbmcvfs, ne open()
        f = xbmcvfs.File(TTS_OUTPUT_PATH, 'w+b')
        f.write(response.content)
        f.close()
        return TTS_OUTPUT_PATH
    except Exception as e:
        raise OpenAITTSException(f'Chyba při generování TTS: {e}') 