# This file was auto-generated by Fern from our API Definition.

import typing
from contextlib import asynccontextmanager, contextmanager

import websockets
import websockets.sync.client as websockets_sync_client
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from .raw_client import AsyncRawTtsClient, RawTtsClient
from .requests.output_format import OutputFormatParams
from .requests.streaming_output_format import StreamingOutputFormatParams
from .requests.voice import VoiceParams
from .socket_client import AsyncTtsSocketClient, TtsSocketClient
from .types.server_sent_event import ServerSentEvent

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class TtsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawTtsClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> RawTtsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawTtsClient
        """
        return self._raw_client

    def bytes(
        self,
        *,
        transcript: str,
        voice: VoiceParams,
        output_format: typing.Optional[OutputFormatParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[bytes]:
        """
        The easiest way to generate text-to-speech audio. Not suitable for latency-sensitive applications.

        Parameters
        ----------
        transcript : str
            Text for narration.

        voice : VoiceParams
            Voice for narration.

        output_format : typing.Optional[OutputFormatParams]
            Audio format specification.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Returns
        -------
        typing.Iterator[bytes]
            WAV file (16-bit LE PCM).

        Examples
        --------
        from respeecher import Respeecher

        client = Respeecher(
            api_key="YOUR_API_KEY",
        )
        client.tts.bytes(
            transcript="Hello, World!",
            voice={"id": "samantha"},
        )
        """
        with self._raw_client.bytes(
            transcript=transcript, voice=voice, output_format=output_format, request_options=request_options
        ) as r:
            yield from r.data

    def sse(
        self,
        *,
        transcript: str,
        voice: VoiceParams,
        output_format: typing.Optional[StreamingOutputFormatParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[ServerSentEvent]:
        """
        Stream text-to-speech audio as JSONL (JSON lines) objects over HTTP. A less performant alternative to WebSockets, without text input streaming.

        Parameters
        ----------
        transcript : str
            Text for narration.

        voice : VoiceParams
            Voice for narration.

        output_format : typing.Optional[StreamingOutputFormatParams]
            Audio format specification.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.Iterator[ServerSentEvent]

        Examples
        --------
        from respeecher import Respeecher

        client = Respeecher(
            api_key="YOUR_API_KEY",
        )
        response = client.tts.sse(
            transcript="Hello, World!",
            voice={"id": "samantha"},
        )
        for chunk in response:
            yield chunk
        """
        with self._raw_client.sse(
            transcript=transcript, voice=voice, output_format=output_format, request_options=request_options
        ) as r:
            yield from r.data

    @contextmanager
    def connect(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.Iterator[TtsSocketClient]:
        """
        A single connection for multiple concurrent text-to-speech generations, with input and output streaming. Provides the best latency and performance out of the text-to-speech endpoints.

        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        TtsSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().ws + "/tts/websocket"
        headers = self._raw_client._client_wrapper.get_headers()
        if request_options and "additional_headers" in request_options:
            headers.update(request_options["additional_headers"])
        try:
            with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol:
                yield TtsSocketClient(websocket=protocol)
        except websockets.exceptions.InvalidStatusCode as exc:
            status_code: int = exc.status_code
            if status_code == 401:
                raise ApiError(
                    status_code=status_code,
                    headers=dict(headers),
                    body="Websocket initialized with invalid credentials.",
                )
            raise ApiError(
                status_code=status_code,
                headers=dict(headers),
                body="Unexpected error when initializing websocket connection.",
            )


class AsyncTtsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawTtsClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> AsyncRawTtsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawTtsClient
        """
        return self._raw_client

    async def bytes(
        self,
        *,
        transcript: str,
        voice: VoiceParams,
        output_format: typing.Optional[OutputFormatParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[bytes]:
        """
        The easiest way to generate text-to-speech audio. Not suitable for latency-sensitive applications.

        Parameters
        ----------
        transcript : str
            Text for narration.

        voice : VoiceParams
            Voice for narration.

        output_format : typing.Optional[OutputFormatParams]
            Audio format specification.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Returns
        -------
        typing.AsyncIterator[bytes]
            WAV file (16-bit LE PCM).

        Examples
        --------
        import asyncio

        from respeecher import AsyncRespeecher

        client = AsyncRespeecher(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.tts.bytes(
                transcript="Hello, World!",
                voice={"id": "samantha"},
            )


        asyncio.run(main())
        """
        async with self._raw_client.bytes(
            transcript=transcript, voice=voice, output_format=output_format, request_options=request_options
        ) as r:
            async for _chunk in r.data:
                yield _chunk

    async def sse(
        self,
        *,
        transcript: str,
        voice: VoiceParams,
        output_format: typing.Optional[StreamingOutputFormatParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[ServerSentEvent]:
        """
        Stream text-to-speech audio as JSONL (JSON lines) objects over HTTP. A less performant alternative to WebSockets, without text input streaming.

        Parameters
        ----------
        transcript : str
            Text for narration.

        voice : VoiceParams
            Voice for narration.

        output_format : typing.Optional[StreamingOutputFormatParams]
            Audio format specification.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.AsyncIterator[ServerSentEvent]

        Examples
        --------
        import asyncio

        from respeecher import AsyncRespeecher

        client = AsyncRespeecher(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            response = await client.tts.sse(
                transcript="Hello, World!",
                voice={"id": "samantha"},
            )
            async for chunk in response:
                yield chunk


        asyncio.run(main())
        """
        async with self._raw_client.sse(
            transcript=transcript, voice=voice, output_format=output_format, request_options=request_options
        ) as r:
            async for _chunk in r.data:
                yield _chunk

    @asynccontextmanager
    async def connect(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.AsyncIterator[AsyncTtsSocketClient]:
        """
        A single connection for multiple concurrent text-to-speech generations, with input and output streaming. Provides the best latency and performance out of the text-to-speech endpoints.

        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncTtsSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().ws + "/tts/websocket"
        headers = self._raw_client._client_wrapper.get_headers()
        if request_options and "additional_headers" in request_options:
            headers.update(request_options["additional_headers"])
        try:
            async with websockets.connect(ws_url, extra_headers=headers) as protocol:
                yield AsyncTtsSocketClient(websocket=protocol)
        except websockets.exceptions.InvalidStatusCode as exc:
            status_code: int = exc.status_code
            if status_code == 401:
                raise ApiError(
                    status_code=status_code,
                    headers=dict(headers),
                    body="Websocket initialized with invalid credentials.",
                )
            raise ApiError(
                status_code=status_code,
                headers=dict(headers),
                body="Unexpected error when initializing websocket connection.",
            )
