__all__ = ["UniWebsocketManager"]

from collections.abc import Awaitable, Callable, Sequence
from typing import Any

from unicex._abc import IUniWebsocketManager
from unicex._base import Websocket
from unicex.enums import Exchange, Timeframe
from unicex.exceptions import NotSupported
from unicex.types import LoggerLike
from unicex.utils import validate_allowed_kwargs

from .adapter import Adapter
from .client import Client
from .uni_client import UniClient
from .websocket_manager import WebsocketManager

type CallbackType = Callable[[Any], Awaitable[None]]


class UniWebsocketManager(IUniWebsocketManager):
    """Реализация менеджера асинхронных унифицированных вебсокетов."""

    def __init__(
        self,
        client: Client | UniClient | None = None,
        logger: LoggerLike | None = None,
        **ws_kwargs: Any,
    ) -> None:
        """Инициализирует унифицированный менеджер вебсокетов.

        Параметры:
            client (`Client | UniClient | None`): Клиент Aster или унифицированный клиент. Нужен для подключения к приватным топикам.
            logger (`LoggerLike | None`): Логгер для записи логов.
            ws_kwargs (`dict[str, Any]`): Дополнительные параметры инициализации, которые будут переданы WebsocketManager/Websocket.
        """
        super().__init__(client=client, logger=logger)
        self._websocket_manager = WebsocketManager(self._client, **ws_kwargs)  # type: ignore
        self._adapter = Adapter()

    def klines(
        self,
        callback: CallbackType,
        timeframe: Timeframe,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        raise NotSupported("Spot market data is not supported for Aster")

    def futures_klines(
        self,
        callback: CallbackType,
        timeframe: Timeframe,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        wrapper = self._make_wrapper(self._adapter.Klines_message, callback)
        return self._websocket_manager.futures_klines(
            callback=wrapper,
            symbol=symbol,
            symbols=symbols,
            interval=timeframe.to_exchange_format(Exchange.ASTER),
        )

    def trades(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        raise NotSupported("Spot market data is not supported for Aster")

    def aggtrades(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        raise NotSupported("Spot market data is not supported for Aster")

    def futures_trades(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        return self.futures_aggtrades(callback, symbol, symbols)  # type: ignore

    def futures_aggtrades(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        wrapper = self._make_wrapper(self._adapter.trades_message, callback)
        return self._websocket_manager.futures_agg_trade(
            callback=wrapper, symbol=symbol, symbols=symbols
        )

    def futures_best_bid_ask(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        wrapper = self._make_wrapper(self._adapter.futures_best_bid_ask_message, callback)
        return self._websocket_manager.futures_symbol_book_ticker(
            callback=wrapper,
            symbol=symbol,
            symbols=symbols,
        )

    def futures_partial_book_depth(
        self,
        callback: CallbackType,
        limit: int,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
        **kwargs: Any,
    ) -> Websocket:
        allowed_levels = {5, 10, 20}
        if limit not in allowed_levels:
            raise ValueError("Parameter `limit` must be one of: 5, 10, 20")

        validate_allowed_kwargs(kwargs=kwargs, allowed_kwargs=("update_speed",))

        update_speed: str | None = kwargs.get("update_speed")
        allowed_update_speeds = {None, "100ms", "500ms"}
        if update_speed not in allowed_update_speeds:
            raise ValueError("Parameter `update_speed` must be one of: '100ms', '500ms' or None")

        wrapper = self._make_wrapper(self._adapter.futures_partial_book_depth_message, callback)
        return self._websocket_manager.futures_partial_book_depth(
            callback=wrapper,
            symbol=symbol,
            symbols=symbols,
            levels=str(limit),
            update_speed=update_speed,
        )
