"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations

import asyncio
from collections import deque
import logging
import struct
import time
import threading
import traceback

from typing import Any, Callable, Coroutine, Dict, List, TYPE_CHECKING, NamedTuple, Optional, Sequence, TypeVar, Tuple

from curl_cffi import CurlError, WebSocketError
from curl_cffi.requests import AsyncWebSocket
from curl_cffi.const import CurlWsFlag
import yarl

from . import utils
from .enums import SpeakingState, Status
from .errors import ClientException, ConnectionClosed
from .flags import Capabilities

try:
    import davey  # type: ignore
except ImportError:
    pass

_log = logging.getLogger(__name__)

__all__ = (
    'DiscordWebSocket',
    'KeepAliveHandler',
    'VoiceKeepAliveHandler',
    'DiscordVoiceWebSocket',
    'ReconnectWebSocket',
    'ConnectionClosed',
)

if TYPE_CHECKING:
    from typing_extensions import Self

    from .client import Client
    from .state import ConnectionState
    from .types.activity import Activity as ActivityPayload
    from .types.snowflake import Snowflake
    from .types.gateway import BulkGuildSubscribePayload
    from .voice_state import VoiceConnectionState


class ReconnectWebSocket(Exception):
    """Signals to safely reconnect the websocket."""

    def __init__(self, *, resume: bool = True):
        self.resume = resume
        self.op: str = 'RESUME' if resume else 'IDENTIFY'


class WebSocketClosure(Exception):
    """An exception to make up for the fact that curl doesn't signal closure.

    Attributes
    -----------
    code: :class:`int`
        The close code of the websocket.
    reason: :class:`str`
        The reason provided for the closure.
    """

    __slots__ = ('code', 'reason')

    def __init__(self, socket: AsyncWebSocket):
        self.code: int = socket.close_code or -1
        self.reason: str = socket.close_reason or ''
        super().__init__(f'Websocket closed with {self.code} (reason: {self.reason!r})')


class EventListener(NamedTuple):
    predicate: Callable[[Dict[str, Any]], bool]
    event: str
    result: Optional[Callable[[Dict[str, Any]], Any]]
    future: asyncio.Future[Any]


class GatewayRatelimiter:
    def __init__(self, count: int = 110, per: float = 60.0) -> None:
        # The default is 110 to give room for at least 10 heartbeats per minute
        self.max: int = count
        self.remaining: int = count
        self.window: float = 0.0
        self.per: float = per
        self.lock: asyncio.Lock = asyncio.Lock()

    def is_ratelimited(self) -> bool:
        current = time.time()
        if current > self.window + self.per:
            return False
        return self.remaining == 0

    def get_delay(self) -> float:
        current = time.time()

        if current > self.window + self.per:
            self.remaining = self.max

        if self.remaining == self.max:
            self.window = current

        if self.remaining == 0:
            return self.per - (current - self.window)

        self.remaining -= 1
        return 0.0

    async def block(self) -> None:
        async with self.lock:
            delta = self.get_delay()
            if delta:
                _log.warning('Gateway is ratelimited, waiting %.2f seconds.', delta)
                await asyncio.sleep(delta)


class KeepAliveHandler:  # Inspired by enhanced-discord.py/Gnome
    def __init__(self, *, ws: DiscordWebSocket, interval: Optional[float] = None):
        self.ws: DiscordWebSocket = ws
        self.interval: Optional[float] = interval
        self.heartbeat_timeout: float = self.ws._max_heartbeat_timeout

        self.msg: str = 'Keeping websocket alive.'
        self.block_msg: str = 'Heartbeat blocked for more than %s seconds.'
        self.behind_msg: str = "Can't keep up, websocket is %.1fs behind."
        self.not_responding_msg: str = 'Gateway has stopped responding. Closing and restarting.'
        self.no_stop_msg: str = 'An error occurred while stopping the Gateway. Ignoring.'

        self._stop: asyncio.Event = asyncio.Event()
        self._last_send: float = time.perf_counter()
        self._last_recv: float = time.perf_counter()
        self._last_ack: float = time.perf_counter()
        self.latency: float = float('inf')

    async def run(self) -> None:
        while True:
            try:
                await asyncio.wait_for(self._stop.wait(), timeout=self.interval)
            except asyncio.TimeoutError:
                pass
            else:
                return

            if self._last_recv + self.heartbeat_timeout < time.perf_counter():
                _log.warning(self.not_responding_msg)

                try:
                    await self.ws.close(4000)
                except Exception:
                    _log.exception(self.no_stop_msg)
                finally:
                    self.stop()
                return

            data = self.get_payload()
            _log.debug(self.msg)
            try:
                total = 0
                while True:
                    try:
                        await asyncio.wait_for(self.ws.send_heartbeat(data), timeout=10)
                        break
                    except asyncio.TimeoutError:
                        total += 10

                        stack = ''.join(traceback.format_stack())
                        msg = f'{self.block_msg}\nLoop traceback (most recent call last):\n{stack}'
                        _log.warning(msg, total)

            except Exception:
                self.stop()
            else:
                self._last_send = time.perf_counter()

    def get_payload(self) -> Dict[str, Any]:
        return {
            'op': self.ws.HEARTBEAT,
            'd': self.ws.sequence,
        }

    def start(self) -> None:
        self.ws.loop.create_task(self.run())

    def stop(self) -> None:
        self._stop.set()

    def tick(self) -> None:
        self._last_recv = time.perf_counter()

    def ack(self) -> None:
        ack_time = time.perf_counter()
        self._last_ack = ack_time
        self.latency = ack_time - self._last_send
        if self.latency > 10:
            _log.warning(self.behind_msg, self.latency)


class VoiceKeepAliveHandler(KeepAliveHandler):
    if TYPE_CHECKING:
        ws: DiscordVoiceWebSocket

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.recent_ack_latencies: deque[float] = deque(maxlen=20)
        self.msg: str = 'Keeping voice socket alive.'
        self.block_msg: str = 'Voice heartbeat blocked for more than %s seconds'
        self.behind_msg: str = 'High voice socket latency, heartbeat is %.1fs behind'
        self.not_responding_msg: str = 'Voice socket has stopped responding. Closing and restarting.'
        self.no_stop_msg: str = 'An error occurred while stopping the voice socket. Ignoring.'

    def get_payload(self) -> Dict[str, Any]:
        return {
            'op': self.ws.HEARTBEAT,
            'd': {
                't': int(time.time() * 1000),
                'seq_ack': self.ws.seq_ack,
            },
        }

    def ack(self) -> None:
        ack_time = time.perf_counter()
        self._last_ack = ack_time
        self._last_recv = ack_time
        self.latency: float = ack_time - self._last_send
        self.recent_ack_latencies.append(self.latency)
        if self.latency > 10:
            _log.warning(self.behind_msg, self.latency)


DWS = TypeVar('DWS', bound='DiscordWebSocket')


class DiscordWebSocket:
    """Implements a WebSocket for Discord's Gateway v9.

    Attributes
    -----------
    gateway
        The Gateway we are currently connected to.
    token
        The authentication token for Discord.
    """

    if TYPE_CHECKING:
        token: Optional[str]
        _connection: ConnectionState
        _discord_parsers: Dict[str, Callable[..., Any]]
        call_hooks: Callable[..., Any]
        _initial_identify: bool
        shard_id: Optional[int]
        shard_count: Optional[int]
        gateway: yarl.URL
        _max_heartbeat_timeout: float
        _headers: utils.Headers
        _transport_compression: bool

    # fmt: off
    DEFAULT_GATEWAY       = yarl.URL('wss://gateway.discord.gg/')
    DISPATCH              = 0
    HEARTBEAT             = 1
    IDENTIFY              = 2
    PRESENCE              = 3
    VOICE_STATE           = 4
    VOICE_PING            = 5
    RESUME                = 6
    RECONNECT             = 7
    REQUEST_MEMBERS       = 8
    INVALIDATE_SESSION    = 9
    HELLO                 = 10
    HEARTBEAT_ACK         = 11
    # GUILD_SYNC          = 12
    CALL_CONNECT          = 13
    GUILD_SUBSCRIBE       = 14  # Deprecated
    # REQUEST_COMMANDS    = 24
    SEARCH_RECENT_MEMBERS = 35
    BULK_GUILD_SUBSCRIBE  = 37
    # fmt: on

    def __init__(self, socket: AsyncWebSocket, *, loop: asyncio.AbstractEventLoop) -> None:
        self.socket: AsyncWebSocket = socket
        self.loop: asyncio.AbstractEventLoop = loop

        # An empty dispatcher to prevent crashes
        self._dispatch: Callable[..., Any] = lambda *args: None
        # Generic event listeners
        self._dispatch_listeners: List[EventListener] = []
        # The keep alive
        self._keep_alive: Optional[KeepAliveHandler] = None
        self.thread_id: int = threading.get_ident()

        # WS related stuff
        self.session_id: Optional[str] = None
        self.sequence: Optional[int] = None
        self._decompressor: utils._DecompressionContext = utils._ActiveDecompressionContext()
        self._close_code: Optional[int] = None
        self._rate_limiter: GatewayRatelimiter = GatewayRatelimiter()

        self._hello_trace: List[str] = []
        self._session_trace: List[str] = []
        self._resume_trace: List[str] = []
        self._initial_identify: bool = False

        # Presence state tracking
        self.status: str = Status.unknown.value
        self.activities: List[ActivityPayload] = []
        self.afk: bool = False
        self.idle_since: int = 0

    @property
    def open(self) -> bool:
        return not self.socket.closed

    @property
    def capabilities(self) -> Capabilities:
        return Capabilities.default()

    def is_ratelimited(self) -> bool:
        return self._rate_limiter.is_ratelimited()

    def debug_log_receive(self, data: Dict[str, Any], /) -> None:
        self._dispatch('socket_raw_receive', data)

    def log_receive(self, _: Dict[str, Any], /) -> None:
        pass

    @classmethod
    async def from_client(
        cls,
        client: Client,
        *,
        initial: bool = False,
        gateway: Optional[yarl.URL] = None,
        session: Optional[str] = None,
        sequence: Optional[int] = None,
        resume: bool = False,
        encoding: str = 'json',
        compress: bool = True,
    ) -> Self:
        """Creates a main websocket for Discord from a :class:`Client`.

        This is for internal use only.
        """
        # Circular import
        from .http import INTERNAL_API_VERSION

        gateway = gateway or cls.DEFAULT_GATEWAY

        if not compress:
            url = gateway.with_query(v=INTERNAL_API_VERSION, encoding=encoding)
        else:
            url = gateway.with_query(
                v=INTERNAL_API_VERSION, encoding=encoding, compress=utils._ActiveDecompressionContext.COMPRESSION_TYPE
            )

        socket = await client.http.ws_connect(str(url))
        ws = cls(socket, loop=client.loop)

        # Dynamically add attributes needed
        ws.token = client.http.token
        ws._connection = client._connection
        ws._discord_parsers = client._connection.parsers
        ws._dispatch = client.dispatch
        ws.gateway = gateway
        ws.call_hooks = client._connection.call_hooks
        ws._initial_identify = initial
        ws.session_id = session
        ws.sequence = sequence
        ws._max_heartbeat_timeout = client._connection.heartbeat_timeout
        ws._headers = client.http.headers
        ws._transport_compression = compress
        ws.afk = client._connection._afk
        ws.idle_since = client._connection._idle_since

        if client._enable_debug_events:
            ws.send = ws.debug_send
            ws.log_receive = ws.debug_log_receive

        client._connection._update_references(ws)
        _log.debug('Connected to %s.', gateway)

        if not resume:
            await ws.identify()
            return ws

        await ws.resume()
        return ws

    def wait_for(
        self,
        event: str,
        predicate: Callable[[Dict[str, Any]], bool],
        result: Optional[Callable[[Dict[str, Any]], Any]] = None,
    ) -> asyncio.Future[Any]:
        """Waits for a DISPATCH'd event that meets the predicate.

        Parameters
        -----------
        event: :class:`str`
            The event to wait for.
        predicate
            A function that takes a data parameter to check for event
            properties. The data parameter is the 'd' key in the JSON message.
        result
            A function that takes the same data parameter and executes to send
            the result to the future. If ``None``, returns the data.

        Returns
        --------
        asyncio.Future
            A future to wait for.
        """

        event = event.upper()
        future = self.loop.create_future()
        entry = EventListener(event=event, predicate=predicate, result=result, future=future)
        self._dispatch_listeners.append(entry)
        return future

    async def identify(self) -> None:
        """Sends the IDENTIFY packet."""

        # User presence is weird...
        # This payload is only sometimes respected; usually the gateway tells
        # us our presence through the READY packet's sessions key
        # However, when reidentifying, we should send our last known presence
        # initial_status and initial_activities could probably also be sent here
        # but that needs more testing...
        presence = {
            'status': 'unknown',
            'since': self.idle_since,
            'activities': [],
            'afk': self.afk,
        }
        existing = self._connection.current_session
        if existing is not None:
            presence['status'] = str(existing.status) if existing.status is not Status.offline else 'invisible'
            presence['activities'] = [a.to_dict() for a in existing.activities]
        # else:
        #     presence['status'] = self._connection._status or 'unknown'
        #     presence['activities'] = self._connection._activities

        properties = self._headers.gateway_properties

        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'capabilities': self.capabilities.value,
                'properties': properties,
                'presence': presence,
                'compress': not self._transport_compression,  # We require at least one form of compression
                'client_state': {
                    'guild_versions': {},
                },
            },
        }

        await self.call_hooks('before_identify', initial=self._initial_identify)
        await self.send_as_json(payload)
        _log.debug('Gateway has sent the IDENTIFY payload.')
        self._initial_identify = True

    async def resume(self) -> None:
        """Sends the RESUME packet."""
        payload = {
            'op': self.RESUME,
            'd': {
                'seq': self.sequence,
                'session_id': self.session_id,
                'token': self.token,
            },
        }

        await self.send_as_json(payload)
        _log.debug('Gateway has sent the RESUME payload.')

    async def received_message(self, msg: Any, /) -> None:
        if type(msg) is bytes:
            msg = self._decompressor.decompress(msg)

            # Received a partial gateway message
            if msg is None:
                return

        self.log_receive(msg)
        msg = utils._from_json(msg)

        _log.debug('Gateway event: %s.', msg)
        event = msg.get('t')
        if event:
            self._dispatch('socket_event_type', event)

        op = msg.get('op')
        data = msg.get('d')
        seq = msg.get('s')
        if seq is not None:
            self.sequence = seq

        if self._keep_alive:
            self._keep_alive.tick()

        if op != self.DISPATCH:
            if op == self.RECONNECT:
                # RECONNECT can only be handled by the Client
                # so we terminate our connection and raise an
                # internal exception signalling to reconnect
                _log.debug('Received RECONNECT opcode.')
                await self.close()
                raise ReconnectWebSocket

            if op == self.HEARTBEAT_ACK:
                if self._keep_alive:
                    self._keep_alive.ack()
                return

            if op == self.HEARTBEAT:
                if self._keep_alive:
                    beat = self._keep_alive.get_payload()
                    await self.send_as_json(beat)
                return

            if op == self.HELLO:
                self._hello_trace = data.get('_trace', [])
                interval = data['heartbeat_interval'] / 1000.0
                self._keep_alive = KeepAliveHandler(ws=self, interval=interval)
                # Send a heartbeat immediately
                await self.send_as_json(self._keep_alive.get_payload())
                self._keep_alive.start()
                return

            if op == self.INVALIDATE_SESSION:
                if data is True:
                    await self.close()
                    raise ReconnectWebSocket

                self.sequence = None
                self.session_id = None
                self.gateway = self.DEFAULT_GATEWAY

                _log.info('Gateway session has been invalidated.')
                await self.close(code=1000)
                raise ReconnectWebSocket(resume=False)

            _log.warning('Unknown OP code %s.', op)
            return

        if event == 'READY':
            self._session_trace = data.get('_trace', [])
            self.sequence = msg['s']
            self.session_id = data['session_id']
            self.gateway = yarl.URL(data['resume_gateway_url'])

            _log.info('Connected to Gateway (session ID: %s).', self.session_id)
            await self.voice_state()  # Initial OP 4

        elif event == 'RESUMED':
            self._resume_trace = data.get('_trace', [])
            _log.info('Gateway has successfully RESUMED session %s.', self.session_id)

        try:
            func = self._discord_parsers[event]
        except KeyError:
            _log.debug('Unknown event %s.', event)
        else:
            try:
                func(data)
            except Exception as exc:
                if event in ('READY', 'READY_SUPPLEMENTAL'):
                    raise
                _log.warning(
                    'Parsing event %s encountered an exception. Please open an issue with this traceback:',
                    event,
                    exc_info=exc,
                )

        # Remove the dispatched listeners
        removed = []
        for index, entry in enumerate(self._dispatch_listeners):
            if entry.event != event:
                continue

            future = entry.future
            if future.cancelled():
                removed.append(index)
                continue

            try:
                valid = entry.predicate(data)
            except Exception as exc:
                future.set_exception(exc)
                removed.append(index)
            else:
                if valid:
                    ret = data if entry.result is None else entry.result(data)
                    future.set_result(ret)
                    removed.append(index)

        for index in reversed(removed):
            del self._dispatch_listeners[index]

    @property
    def latency(self) -> float:
        """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds."""
        heartbeat = self._keep_alive
        return float('inf') if heartbeat is None else heartbeat.latency

    def _can_handle_close(self, code: Optional[int] = None) -> bool:
        code = code or self._close_code
        # If the socket is closed remotely with 1000 and it's not our own explicit close
        # then it's an improper close that should be handled and reconnected
        is_improper_close = self._close_code is None and code == 1000
        return is_improper_close or code not in (1000, 4004, 4010, 4011, 4012, 4013, 4014)

    async def poll_event(self) -> None:
        """Polls for a DISPATCH event and handles the general Gateway loop.

        Raises
        ------
        ConnectionClosed
            The websocket connection was terminated for unhandled reasons.
        """
        try:
            msg, flags = await asyncio.wait_for(self.socket.recv(), timeout=self._max_heartbeat_timeout)
            if (flags & CurlWsFlag.TEXT) or (flags & CurlWsFlag.BINARY):
                await self.received_message(msg)
            elif flags & CurlWsFlag.CLOSE:
                socket = self.socket
                raise WebSocketClosure(socket)
        except (asyncio.TimeoutError, CurlError, WebSocketClosure) as e:
            _log.debug('Got Gateway poll exception: %s.', type(e), exc_info=True)
            # Ensure the keep alive handler is closed
            if self._keep_alive:
                self._keep_alive.stop()
                self._keep_alive = None

            if isinstance(e, asyncio.TimeoutError):
                _log.debug('Timed out receiving Gateway packet. Attempting a reconnect.')
                raise ReconnectWebSocket from None

            socket = self.socket
            code = self._close_code or socket.close_code
            reason = socket.close_reason
            if isinstance(e, CurlError):
                reason = str(e)

            if not socket.closed:
                await socket.close(code or 4000, (reason or 'Unknown error').encode('utf-8'))

            _log.info('Gateway received close code %s and reason %r.', code, reason)

            if self._can_handle_close(code or None):
                _log.debug('Websocket closed with %s, attempting a reconnect.', code)
                raise ReconnectWebSocket from None
            else:
                _log.debug('Websocket closed with %s, cannot reconnect.', code)
                raise ConnectionClosed(code, reason) from None
        except asyncio.CancelledError:
            if self._keep_alive:
                self._keep_alive.stop()
                self._keep_alive = None
            raise

    async def _sendstr(self, data: str, /, *, raise_on_closed: bool = False) -> None:
        try:
            await self.socket.send(data.encode('utf-8'))
        except WebSocketError:
            if self.socket.closed:
                # Not much we can do here
                _log.debug('Websocket is closed, cannot send data.')
                if raise_on_closed:
                    raise ClientException('WebSocket is closed')
            else:
                raise

    async def debug_send(self, data: str, /, *, raise_on_closed: bool = False) -> None:
        await self._rate_limiter.block()
        self._dispatch('socket_raw_send', data)
        await self._sendstr(data, raise_on_closed=raise_on_closed)

    async def send(self, data: str, /, *, raise_on_closed: bool = False) -> None:
        await self._rate_limiter.block()
        await self._sendstr(data, raise_on_closed=raise_on_closed)

    async def send_as_json(self, data: Any, /, *, raise_on_closed: bool = False) -> None:
        try:
            await self.send(utils._to_json(data), raise_on_closed=raise_on_closed)
        except RuntimeError as exc:
            if not self._can_handle_close(self._close_code):
                raise ConnectionClosed(self._close_code) from exc

    async def send_heartbeat(self, data: Any, /) -> None:
        # This bypasses the rate limit handling code since it has a higher priority
        try:
            await self._sendstr(utils._to_json(data))
        except RuntimeError as exc:
            if not self._can_handle_close(self._close_code):
                raise ConnectionClosed(self._close_code) from exc

    async def change_presence(
        self,
        *,
        activities: Optional[Sequence[ActivityPayload]] = None,
        status: str,
        since: int = 0,
        afk: bool = False,
    ) -> None:
        payload = {
            'op': self.PRESENCE,
            'd': {'activities': activities or [], 'afk': afk, 'since': since, 'status': str(status)},
        }

        _log.debug('Sending %s to change presence.', payload['d'])
        await self.send_as_json(payload)
        self.status = str(status)
        self.activities = list(activities or [])
        self.afk = afk
        self.idle_since = since

    async def guild_subscribe(
        self,
        guild_id: Snowflake,
        *,
        typing: Optional[bool] = None,
        threads: Optional[bool] = None,
        activities: Optional[bool] = None,
        members: Optional[List[Snowflake]] = None,
        channels: Optional[Dict[Snowflake, List[List[int]]]] = None,
        thread_member_lists: Optional[List[Snowflake]] = None,
    ):
        payload = {
            'op': self.GUILD_SUBSCRIBE,
            'd': {
                'guild_id': str(guild_id),
            },
        }

        data = payload['d']
        if typing is not None:
            data['typing'] = typing
        if threads is not None:
            data['threads'] = threads
        if activities is not None:
            data['activities'] = activities
        if members is not None:
            data['members'] = members
        if channels is not None:
            data['channels'] = channels
        if thread_member_lists is not None:
            data['thread_member_lists'] = thread_member_lists

        _log.debug('Subscribing to guild %s with payload %s', guild_id, payload['d'])
        await self.send_as_json(payload)

    async def bulk_guild_subscribe(self, subscriptions: BulkGuildSubscribePayload) -> None:
        payload = {
            'op': self.BULK_GUILD_SUBSCRIBE,
            'd': {
                'subscriptions': subscriptions,
            },
        }

        _log.debug('Subscribing to guilds with payload %s', payload['d'])
        await self.send_as_json(payload, raise_on_closed=True)

    async def request_chunks(
        self,
        guild_ids: List[Snowflake],
        query: Optional[str] = None,
        *,
        limit: Optional[int] = None,
        user_ids: Optional[List[Snowflake]] = None,
        presences: bool = True,
        nonce: Optional[str] = None,
    ) -> None:
        payload = {
            'op': self.REQUEST_MEMBERS,
            'd': {
                'guild_id': guild_ids,
                'query': query,
                'limit': limit,
                'presences': presences,
                'user_ids': user_ids,
            },
        }

        if nonce is not None:
            payload['d']['nonce'] = nonce

        await self.send_as_json(payload)

    async def voice_state(
        self,
        guild_id: Optional[int] = None,
        channel_id: Optional[int] = None,
        self_mute: bool = False,
        self_deaf: bool = False,
        self_video: bool = False,
    ) -> None:
        payload = {
            'op': self.VOICE_STATE,
            'd': {
                'guild_id': guild_id,
                'channel_id': channel_id,
                'self_mute': self_mute,
                'self_deaf': self_deaf,
                'self_video': self_video,
            },
        }

        if channel_id:
            payload['d'].update(self._connection._get_preferred_regions())

        _log.debug('Updating %s voice state to %s.', guild_id or 'client', payload)
        await self.send_as_json(payload)

    async def call_connect(self, channel_id: Snowflake):
        payload = {'op': self.CALL_CONNECT, 'd': {'channel_id': str(channel_id)}}

        _log.debug('Requesting call connect for channel %s.', channel_id)
        await self.send_as_json(payload)

    async def search_recent_members(
        self, guild_id: Snowflake, query: str = '', *, after: Optional[Snowflake] = None, nonce: Optional[str] = None
    ) -> None:
        payload = {
            'op': self.SEARCH_RECENT_MEMBERS,
            'd': {
                'guild_id': str(guild_id),
                'query': query,
                'continuation_token': str(after) if after else None,
            },
        }
        if nonce is not None:
            payload['d']['nonce'] = nonce

        await self.send_as_json(payload)

    async def close(self, code: int = 4000, reason: bytes = b'') -> None:
        _log.debug(f'Closing websocket with code {code}.')
        if self._keep_alive:
            self._keep_alive.stop()
            self._keep_alive = None

        self._close_code = code
        try:
            await self.socket.close(code, reason)
        except Exception:
            _log.debug('Ignoring exception closing Gateway socket.', exc_info=True)


DVWS = TypeVar('DVWS', bound='DiscordVoiceWebSocket')


class DiscordVoiceWebSocket:
    """Implements the websocket protocol for handling voice connections."""

    if TYPE_CHECKING:
        thread_id: int
        _connection: VoiceConnectionState
        gateway: str
        _max_heartbeat_timeout: float

    # fmt: off
    IDENTIFY                       = 0
    SELECT_PROTOCOL                = 1
    READY                          = 2
    HEARTBEAT                      = 3
    SESSION_DESCRIPTION            = 4
    SPEAKING                       = 5
    HEARTBEAT_ACK                  = 6
    RESUME                         = 7
    HELLO                          = 8
    RESUMED                        = 9
    CLIENTS_CONNECT                = 11
    VIDEO                          = 12
    CLIENT_DISCONNECT              = 13
    VOICE_BACKEND_VERSION          = 16
    DAVE_PREPARE_TRANSITION        = 21
    DAVE_EXECUTE_TRANSITION        = 22
    DAVE_TRANSITION_READY          = 23
    DAVE_PREPARE_EPOCH             = 24
    MLS_EXTERNAL_SENDER            = 25
    MLS_KEY_PACKAGE                = 26
    MLS_PROPOSALS                  = 27
    MLS_COMMIT_WELCOME             = 28
    MLS_ANNOUNCE_COMMIT_TRANSITION = 29
    MLS_WELCOME                    = 30
    MLS_INVALID_COMMIT_WELCOME     = 31
    # fmt: on

    def __init__(
        self,
        socket: AsyncWebSocket,
        loop: asyncio.AbstractEventLoop,
        *,
        hook: Optional[Callable[..., Coroutine[Any, Any, None]]] = None,
    ) -> None:
        self.ws: AsyncWebSocket = socket
        self.loop: asyncio.AbstractEventLoop = loop
        self._keep_alive: Optional[VoiceKeepAliveHandler] = None
        self._close_code: Optional[int] = None
        self.secret_key: Optional[List[int]] = None
        self.seq_ack: int = -1
        self.voice_version: Optional[str] = None
        self.rtc_worker_version: Optional[str] = None
        if hook:
            self._hook = hook  # type: ignore

    async def _hook(self, *args: Any) -> None:
        pass

    async def _sendstr(self, data: str, /) -> None:
        try:
            await self.ws.send_str(data)
        except WebSocketError:
            if self.ws.closed:
                # Not much we can do here
                _log.debug('Voice socket is closed, cannot send data.')
            else:
                raise

    async def send_as_json(self, data: Any) -> None:
        _log.debug('Voice socket sending: %s.', data)
        await self._sendstr(utils._to_json(data))

    async def send_binary(self, opcode: int, data: bytes) -> None:
        _log.debug('Voice socket sending binary: opcode=%s, size=%d.', opcode, len(data))
        await self.ws.send_bytes(bytes([opcode]) + data)

    send_heartbeat = send_as_json

    async def resume(self) -> None:
        state = self._connection
        payload = {
            'op': self.RESUME,
            'd': {
                'token': state.token,
                'server_id': str(state.server_id),
                'session_id': state.session_id,
                'seq_ack': self.seq_ack,
            },
        }
        await self.send_as_json(payload)

    async def identify(self) -> None:
        state = self._connection
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'server_id': str(state.server_id),
                'user_id': str(state.user.id),
                'session_id': state.session_id,
                'token': state.token,
                'max_dave_protocol_version': state.max_dave_protocol_version,
            },
        }
        await self.send_as_json(payload)

    @classmethod
    async def from_connection_state(
        cls,
        state: VoiceConnectionState,
        *,
        resume: bool = False,
        hook: Optional[Callable[..., Coroutine[Any, Any, Any]]] = None,
        seq_ack: int = -1,
    ) -> Self:
        """Creates a voice websocket for the :class:`VoiceClient`."""
        gateway = f'wss://{state.endpoint}/?v=8'
        client = state.voice_client
        http = client._state.http
        socket = await http.ws_connect(gateway)
        ws = cls(socket, loop=client.loop, hook=hook)
        ws.gateway = gateway
        ws.seq_ack = seq_ack
        ws._connection = state
        ws._max_heartbeat_timeout = 60.0
        ws.thread_id = threading.get_ident()

        if resume:
            await ws.resume()
        else:
            await ws.identify()

        return ws

    async def select_protocol(self, ip: str, port: int, mode: str) -> None:
        payload = {
            'op': self.SELECT_PROTOCOL,
            'd': {
                'protocol': 'udp',
                'data': {
                    'address': ip,
                    'port': port,
                    'mode': mode,
                },
            },
        }

        await self.send_as_json(payload)

    async def client_connect(self) -> None:
        payload = {
            'op': self.VIDEO,
            'd': {
                'audio_ssrc': self._connection.ssrc,
            },
        }

        await self.send_as_json(payload)

    async def speak(self, state: SpeakingState = SpeakingState.voice) -> None:
        payload = {
            'op': self.SPEAKING,
            'd': {
                'speaking': int(state),
                'delay': 0,
                'ssrc': self._connection.ssrc,
            },
        }

        await self.send_as_json(payload)

    async def request_voice_backend_version(self) -> None:
        payload = {
            'op': self.VOICE_BACKEND_VERSION,
            'd': {},
        }

        await self.send_as_json(payload)

    async def send_transition_ready(self, transition_id: int):
        payload = {
            'op': DiscordVoiceWebSocket.DAVE_TRANSITION_READY,
            'd': {
                'transition_id': transition_id,
            },
        }

        await self.send_as_json(payload)

    async def received_message(self, msg: Dict[str, Any]) -> None:
        _log.debug('Voice socket event: %s.', msg)
        op = msg['op']
        data = msg['d']  # According to Discord this key is always given
        self.seq_ack = msg.get('seq', self.seq_ack)

        if op == self.READY:
            await self.initial_connection(data)
        elif op == self.HEARTBEAT_ACK:
            if self._keep_alive:
                self._keep_alive.ack()
        elif op == self.RESUMED:
            _log.debug('Voice RESUME succeeded.')
        elif op == self.SESSION_DESCRIPTION:
            self._connection.mode = data['mode']
            await self.load_secret_key(data)
            self._connection.dave_protocol_version = data['dave_protocol_version']
            if data['dave_protocol_version'] > 0:
                await self._connection.reinit_dave_session()
        elif op == self.HELLO:
            interval = data['heartbeat_interval'] / 1000.0
            self._keep_alive = VoiceKeepAliveHandler(ws=self, interval=interval)
            self._keep_alive.start()
        elif op == self.VOICE_BACKEND_VERSION:
            self.voice_version = data.get('voice')
            self.rtc_worker_version = data.get('rtc_worker')
            _log.debug('Voice backend version: voice=%r, rtc_worker=%r.', self.voice_version, self.rtc_worker_version)
        elif self._connection.dave_session:
            state = self._connection
            if op == self.DAVE_PREPARE_TRANSITION:
                _log.debug(
                    'Preparing for DAVE transition ID %d for protocol version %d.',
                    data['transition_id'],
                    data['protocol_version'],
                )
                state.dave_pending_transitions[data['transition_id']] = data['protocol_version']
                if data['transition_id'] == 0:
                    await state._execute_transition(data['transition_id'])
                else:
                    if data['protocol_version'] == 0 and state.dave_session:
                        state.dave_session.set_passthrough_mode(True, 120)

                    await self.send_transition_ready(data['transition_id'])
            elif op == self.DAVE_EXECUTE_TRANSITION:
                _log.debug('Executing DAVE transition ID %d.', data['transition_id'])
                await state._execute_transition(data['transition_id'])
            elif op == self.DAVE_PREPARE_EPOCH:
                _log.debug('Preparing for DAVE epoch %d.', data['epoch'])
                # When the epoch ID is equal to 1, this message indicates that a new MLS group is to be created for the given protocol version.
                if data['epoch'] == 1:
                    state.dave_protocol_version = data['protocol_version']
                    await state.reinit_dave_session()

        await self._hook(self, msg)

    async def received_binary_message(self, msg: bytes) -> None:
        self.seq_ack = struct.unpack_from('>H', msg, 0)[0]
        op = msg[2]
        _log.debug('Voice socket binary frame: %d bytes, seq=%s, op=%s.', len(msg), self.seq_ack, op)
        state = self._connection

        if state.dave_session is None:
            return

        if op == self.MLS_EXTERNAL_SENDER:
            state.dave_session.set_external_sender(msg[3:])
            _log.debug('Set MLS external sender.')
        elif op == self.MLS_PROPOSALS:
            optype = msg[3]
            result = state.dave_session.process_proposals(
                davey.ProposalsOperationType.append if optype == 0 else davey.ProposalsOperationType.revoke, msg[4:]
            )
            if isinstance(result, davey.CommitWelcome):
                await self.send_binary(
                    DiscordVoiceWebSocket.MLS_COMMIT_WELCOME,
                    result.commit + result.welcome if result.welcome else result.commit,
                )
            _log.debug('MLS proposals processed.')
        elif op == self.MLS_ANNOUNCE_COMMIT_TRANSITION:
            transition_id = struct.unpack_from('>H', msg, 3)[0]
            try:
                state.dave_session.process_commit(msg[5:])
                if transition_id != 0:
                    state.dave_pending_transitions[transition_id] = state.dave_protocol_version
                    await self.send_transition_ready(transition_id)
                _log.debug('MLS commit processed for transition ID %d.', transition_id)
            except Exception:
                await state._recover_from_invalid_commit(transition_id)
        elif op == self.MLS_WELCOME:
            transition_id = struct.unpack_from('>H', msg, 3)[0]
            try:
                state.dave_session.process_welcome(msg[5:])
                if transition_id != 0:
                    state.dave_pending_transitions[transition_id] = state.dave_protocol_version
                    await self.send_transition_ready(transition_id)
                _log.debug('MLS welcome processed for transition ID %d.', transition_id)
            except Exception:
                await state._recover_from_invalid_commit(transition_id)

    async def initial_connection(self, data: Dict[str, Any]) -> None:
        state = self._connection
        state.ssrc = data['ssrc']
        state.voice_port = data['port']
        state.endpoint_ip = data['ip']

        await self.request_voice_backend_version()
        _log.debug('Connecting to voice socket...')
        await self.loop.sock_connect(state.socket, (state.endpoint_ip, state.voice_port))

        state.ip, state.port = await self.discover_ip()
        modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes]
        _log.debug('Received supported encryption modes: %s.', ', '.join(modes))

        mode = modes[0]
        await self.select_protocol(state.ip, state.port, mode)
        _log.debug('Selected the voice protocol for use: %s.', mode)

    async def discover_ip(self) -> Tuple[str, int]:
        state = self._connection
        packet = bytearray(74)
        struct.pack_into('>H', packet, 0, 1)  # 1 = Send
        struct.pack_into('>H', packet, 2, 70)  # 70 = Length
        struct.pack_into('>I', packet, 4, state.ssrc)

        _log.debug('Sending IP discovery packet...')
        await self.loop.sock_sendall(state.socket, packet)

        fut: asyncio.Future[bytes] = self.loop.create_future()

        def get_ip_packet(data: bytes):
            if data[1] == 0x02 and len(data) == 74:
                self.loop.call_soon_threadsafe(fut.set_result, data)

        fut.add_done_callback(lambda f: state.remove_socket_listener(get_ip_packet))
        state.add_socket_listener(get_ip_packet)
        recv = await fut

        _log.debug('Received IP discovery packet: %s.', recv)

        # The IP is ascii starting at the 8th byte and ending at the first null
        ip_start = 8
        ip_end = recv.index(0, ip_start)
        ip = recv[ip_start:ip_end].decode('ascii')

        port = struct.unpack_from('>H', recv, len(recv) - 2)[0]
        _log.debug('Detected IP: %s, port: %s.', ip, port)

        return ip, port

    @property
    def latency(self) -> float:
        """:class:`float`: Latency between a HEARTBEAT and its HEARTBEAT_ACK in seconds."""
        heartbeat = self._keep_alive
        return float('inf') if heartbeat is None else heartbeat.latency

    @property
    def average_latency(self) -> float:
        """:class:`float`: Average of last 20 HEARTBEAT latencies."""
        heartbeat = self._keep_alive
        if heartbeat is None or not heartbeat.recent_ack_latencies:
            return float('inf')

        return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies)

    async def load_secret_key(self, data: Dict[str, Any]) -> None:
        _log.debug('Received secret key for voice connection.')
        self.secret_key = self._connection.secret_key = data['secret_key']

        # Send a speak command with the "not speaking" state
        # This also tells Discord our SSRC value, which Discord requires before
        # sending any voice data (and is the real reason why we call this here)
        await self.speak(SpeakingState.none)

    async def poll_event(self) -> None:
        # This exception is handled up the chain
        msg, flags = await asyncio.wait_for(self.ws.recv(), timeout=self._max_heartbeat_timeout)
        if msg is None:
            # Should never happen
            return

        if flags & CurlWsFlag.TEXT:
            await self.received_message(utils._from_json(msg))
        elif flags & CurlWsFlag.BINARY:
            await self.received_binary_message(msg)
        elif flags & CurlWsFlag.CLOSE:
            socket = self.ws
            _log.info(f'Voice socket received close code {socket.close_code} and reason {socket.close_reason!r}.')
            raise ConnectionClosed(socket.close_code or self._close_code, socket.close_reason or '')

    async def close(self, code: int = 1000, reason: bytes = b'') -> None:
        if self._keep_alive:
            self._keep_alive.stop()

        self._close_code = code
        try:
            await self.ws.close(code, reason)
        except Exception:
            _log.debug('Ignoring exception closing voice socket.', exc_info=True)
