from __future__ import annotations

import unittest
from unittest import mock

import httpx

from app.livekit.adapters.azure_rest_tts import AzureRESTTTS


class AzureRESTTTSTests(unittest.TestCase):
    def test_request_endpoints_keep_explicit_tts_path(self) -> None:
        tts = AzureRESTTTS(
            voice="pt-BR-FranciscaNeural",
            speech_key="key-123",
            speech_region="brazilsouth",
            speech_endpoint="https://speech.example.cognitiveservices.azure.com/tts/cognitiveservices/v1",
        )

        self.assertEqual(
            tts._request_endpoints(),
            ["https://speech.example.cognitiveservices.azure.com/tts/cognitiveservices/v1"],
        )

    def test_synthesize_pcm_tries_voice_path_after_base_404_for_custom_voice(self) -> None:
        tts = AzureRESTTTS(
            voice="pt-BR-FranciscaNeural",
            speech_key="key-123",
            speech_endpoint="https://speech.example.cognitiveservices.azure.com/cognitiveservices/v1",
            deployment_id="deployment-42",
        )

        base_url = "https://speech.example.cognitiveservices.azure.com/cognitiveservices/v1?deploymentId=deployment-42"
        voice_url = "https://speech.example.cognitiveservices.azure.com/voice/cognitiveservices/v1?deploymentId=deployment-42"

        response_404 = httpx.Response(404, request=httpx.Request("POST", base_url))
        response_ok = httpx.Response(200, content=b"\x00\x00", request=httpx.Request("POST", voice_url))

        with mock.patch.object(httpx.Client, "post", side_effect=[response_404, response_ok]) as mocked_post:
            audio = tts.synthesize_pcm("teste")

        self.assertEqual(audio, b"\x00\x00")
        self.assertEqual([call.args[0] for call in mocked_post.call_args_list], [base_url, voice_url])


if __name__ == "__main__":
    unittest.main()
