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

import typing
import urllib.parse
from contextlib import asynccontextmanager, contextmanager

import websockets.sync.client as websockets_sync_client
from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.jsonable_encoder import jsonable_encoder
from ...core.query_encoder import encode_query
from ...core.remove_none_from_dict import remove_none_from_dict
from ...core.request_options import RequestOptions
from ...core.websocket_compat import InvalidWebSocketStatus, get_status_code
from .raw_client import AsyncRawStreamingTtsClient, RawStreamingTtsClient
from .socket_client import AsyncStreamingTtsSocketClient, StreamingTtsSocketClient

try:
    from websockets.legacy.client import connect as websockets_client_connect  # type: ignore
except ImportError:
    from websockets import connect as websockets_client_connect  # type: ignore


class StreamingTtsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawStreamingTtsClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawStreamingTtsClient
        """
        return self._raw_client

    @contextmanager
    def connect(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.Iterator[StreamingTtsSocketClient]:
        """
        The Lightning SSE API allows you to stream text-to-speech audio in real-time. This is particularly useful for applications requiring low-latency audio generation.

        ### Connection

        Connect to the SSE endpoint:

        ```javascript
        const eventSource = new EventSource(
          'https://api.smallest.ai/api/v1/lightning/stream',
          {
            headers: {
              Authorization: 'Bearer YOUR_API_KEY'
            }
          }
        );
        ```

        ### Request Format

        Send a POST request with the following JSON structure:

        ```json
        {
          "text": "Your text to be converted to speech",
          "voice_id": "voice_id_here",
          "speed": 1,
          "sample_rate": 24000
        }
        ```

        #### Parameters

        | Parameter     | Type   | Required | Description                                         |
        | ------------- | ------ | -------- | --------------------------------------------------- |
        | `text`        | string | Yes      | The text to convert to speech (max 1000 characters) |
        | `voice_id`    | string | Yes      | ID of the voice to use                              |
        | `speed`       | number | No       | Speech speed multiplier (default: 1)                |
        | `sample_rate` | number | No       | Audio sample rate in Hz (default: 24000)            |

        ### Example Usage

        ```javascript
        const eventSource = new EventSource(
          'https://api.smallest.ai/api/v1/lightning/stream',
          {
            headers: {
              Authorization: 'Bearer YOUR_API_KEY'
            }
          }
        );

        // Handle incoming audio chunks
        eventSource.onmessage = (event) => {
          const response = JSON.parse(event.data);

          if (response.status === 'chunk') {
            // Decode and play audio
            const audioData = atob(response.data.audio);
            // Process audio data...
          } else if (response.status === 'complete' && response.done) {
            console.log('All audio chunks received');
            eventSource.close();
          } else if (response.status === 'error') {
            console.error('Error:', response.message);
            eventSource.close();
          }
        };

        eventSource.onerror = (error) => {
          console.error('SSE error:', error);
          eventSource.close();
        };
        ```

        ### Response Events

        The server will send events with the following formats:

        #### Chunk Event

        ```json
        {
          "request_id": "047c9091-b770-41d8-b96b-907d1c8406c0",
          "status": "chunk",
          "data": {
            "audio": "base64_encoded_audio_data"
          }
        }
        ```

        #### Complete Event

        ```json
        {
          "request_id": "047c9091-b770-41d8-b96b-907d1c8406c0",
          "status": "complete",
          "message": "All chunks sent",
          "done": true
        }
        ```

        #### Error Event

        ```json
        {
          "status": "error",
          "message": "Error message",
          "errors": [
            /* detailed error information * /
          ]
        }
        ```

        ### Notes

        - The API automatically chunks long text and streams each chunk separately
        - Credits are deducted based on the length of the input text
        - The SSE connection will remain open until all chunks are sent or an error occurs
        - For optimal performance, keep individual requests under 1000 characters

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

        Returns
        -------
        StreamingTtsSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().waves_ws + "/api/v1/streaming-tts/stream"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        **(
                            request_options.get("additional_query_parameters", {}) or {}
                            if request_options is not None
                            else {}
                        ),
                    }
                )
            )
        )
        if _encoded_query_params:
            ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params)
        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 StreamingTtsSocketClient(websocket=protocol)
        except InvalidWebSocketStatus as exc:
            status_code: int = get_status_code(exc)
            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 AsyncStreamingTtsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawStreamingTtsClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawStreamingTtsClient
        """
        return self._raw_client

    @asynccontextmanager
    async def connect(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.AsyncIterator[AsyncStreamingTtsSocketClient]:
        """
        The Lightning SSE API allows you to stream text-to-speech audio in real-time. This is particularly useful for applications requiring low-latency audio generation.

        ### Connection

        Connect to the SSE endpoint:

        ```javascript
        const eventSource = new EventSource(
          'https://api.smallest.ai/api/v1/lightning/stream',
          {
            headers: {
              Authorization: 'Bearer YOUR_API_KEY'
            }
          }
        );
        ```

        ### Request Format

        Send a POST request with the following JSON structure:

        ```json
        {
          "text": "Your text to be converted to speech",
          "voice_id": "voice_id_here",
          "speed": 1,
          "sample_rate": 24000
        }
        ```

        #### Parameters

        | Parameter     | Type   | Required | Description                                         |
        | ------------- | ------ | -------- | --------------------------------------------------- |
        | `text`        | string | Yes      | The text to convert to speech (max 1000 characters) |
        | `voice_id`    | string | Yes      | ID of the voice to use                              |
        | `speed`       | number | No       | Speech speed multiplier (default: 1)                |
        | `sample_rate` | number | No       | Audio sample rate in Hz (default: 24000)            |

        ### Example Usage

        ```javascript
        const eventSource = new EventSource(
          'https://api.smallest.ai/api/v1/lightning/stream',
          {
            headers: {
              Authorization: 'Bearer YOUR_API_KEY'
            }
          }
        );

        // Handle incoming audio chunks
        eventSource.onmessage = (event) => {
          const response = JSON.parse(event.data);

          if (response.status === 'chunk') {
            // Decode and play audio
            const audioData = atob(response.data.audio);
            // Process audio data...
          } else if (response.status === 'complete' && response.done) {
            console.log('All audio chunks received');
            eventSource.close();
          } else if (response.status === 'error') {
            console.error('Error:', response.message);
            eventSource.close();
          }
        };

        eventSource.onerror = (error) => {
          console.error('SSE error:', error);
          eventSource.close();
        };
        ```

        ### Response Events

        The server will send events with the following formats:

        #### Chunk Event

        ```json
        {
          "request_id": "047c9091-b770-41d8-b96b-907d1c8406c0",
          "status": "chunk",
          "data": {
            "audio": "base64_encoded_audio_data"
          }
        }
        ```

        #### Complete Event

        ```json
        {
          "request_id": "047c9091-b770-41d8-b96b-907d1c8406c0",
          "status": "complete",
          "message": "All chunks sent",
          "done": true
        }
        ```

        #### Error Event

        ```json
        {
          "status": "error",
          "message": "Error message",
          "errors": [
            /* detailed error information * /
          ]
        }
        ```

        ### Notes

        - The API automatically chunks long text and streams each chunk separately
        - Credits are deducted based on the length of the input text
        - The SSE connection will remain open until all chunks are sent or an error occurs
        - For optimal performance, keep individual requests under 1000 characters

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

        Returns
        -------
        AsyncStreamingTtsSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().waves_ws + "/api/v1/streaming-tts/stream"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        **(
                            request_options.get("additional_query_parameters", {}) or {}
                            if request_options is not None
                            else {}
                        ),
                    }
                )
            )
        )
        if _encoded_query_params:
            ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params)
        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_client_connect(ws_url, extra_headers=headers) as protocol:
                yield AsyncStreamingTtsSocketClient(websocket=protocol)
        except InvalidWebSocketStatus as exc:
            status_code: int = get_status_code(exc)
            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.",
            )
