# Fixed test file
import pytest
import aiohttp
import asyncio
import base64
from aioresponses import aioresponses
from app.core.providers.tts.gemini import GeminiTTSProvider
from app.core.providers.base import TTSProvider

@pytest.mark.asyncio
async def test_generate_speech_success():
    """
    Tests that generate_speech correctly makes an API call and processes the response.
    """
    api_key = "test_api_key"
    text_to_speak = "Hello, world!"
    model_name = "gemini-2.5-flash-preview-tts"

    # Create a dummy base64 encoded audio response
    dummy_audio_bytes = b"This is a test audio stream."
    dummy_base64_data = base64.b64encode(dummy_audio_bytes).decode('utf-8')

    # The mocked JSON response from the API
    mock_response_json = {
        "candidates": [{
            "content": {
                "parts": [{
                    "inlineData": {
                        "data": dummy_base64_data
                    }
                }]
            }
        }]
    }

    # Configure aioresponses to intercept the API call and return our mock data
    tts_provider = GeminiTTSProvider(api_key=api_key, model_name=model_name)
    with aioresponses() as m:
        m.post(
            tts_provider.api_url,
            status=200,
            payload=mock_response_json,
            repeat=True
        )

        # Call the method under test, now awaiting the coroutine
        audio_data = await tts_provider.generate_speech(text_to_speak)

        # Assert that the returned data is correct
        assert audio_data == dummy_audio_bytes

def test_init_with_valid_voice_name():
    """
    Tests that initialization succeeds with a valid voice name.
    """
    api_key = "test_api_key"
    voice_name = "Zephyr"
    tts_provider = GeminiTTSProvider(api_key=api_key, voice_name=voice_name)
    assert tts_provider.api_key == api_key
    assert tts_provider.voice_name == voice_name
    assert tts_provider.model_name == "gemini-2.5-flash-preview-tts"
    assert "gemini-2.5-flash-preview-tts" in tts_provider.api_url

def test_init_with_invalid_voice_name():
    """
    Tests that initialization fails with an invalid voice name.
    """
    api_key = "test_api_key"
    invalid_voice_name = "InvalidVoice"
    with pytest.raises(ValueError, match="Invalid voice name"):
        GeminiTTSProvider(api_key=api_key, voice_name=invalid_voice_name)

def test_init_with_custom_model_name():
    """
    Tests that the provider can be initialized with a custom model name.
    """
    api_key = "test_api_key"
    custom_model_name = "gemini-tts-beta"
    tts_provider = GeminiTTSProvider(api_key=api_key, model_name=custom_model_name)
    assert tts_provider.model_name == custom_model_name
    assert custom_model_name in tts_provider.api_url