__all__ = ["IUniWebsocketManager"]

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, MarketType, Timeframe
from unicex.types import LoggerLike

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`): Клиент Gateio или унифицированный клиент. Нужен для подключения к приватным топикам.
            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 _is_service_message(self, raw_msg: Any) -> bool:
        is_sub_msg = raw_msg.get("event") == "subscribe"
        is_pong_msg = raw_msg.get("event") == "pong"
        is_pong_msg_2 = raw_msg.get("channel") in ["spot.pong", "futures.pong"]
        return is_sub_msg or is_pong_msg or is_pong_msg_2

    def _normalize_symbols(
        self,
        symbol: str | None,
        symbols: Sequence[str] | None,
    ) -> list[str]:
        if symbol and symbols:
            raise ValueError("Parameters symbol and symbols cannot be used together")
        if symbol:
            return [symbol]
        if symbols:
            return list(symbols)
        raise ValueError("Either symbol or symbols must be provided")

    def klines(
        self,
        callback: CallbackType,
        timeframe: Timeframe,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        tickers = self._normalize_symbols(symbol, symbols)

        wrapper = self._make_wrapper(self._adapter.klines_message, callback)
        return self._websocket_manager.candlesticks(
            callback=wrapper,
            interval=timeframe.to_exchange_format(Exchange.GATE, MarketType.SPOT),
            symbols=tickers,
        )

    def futures_klines(
        self,
        callback: CallbackType,
        timeframe: Timeframe,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        tickers = self._normalize_symbols(symbol, symbols)

        wrapper = self._make_wrapper(self._adapter.futures_klines_message, callback)
        return self._websocket_manager.futures_candlesticks(
            callback=wrapper,
            interval=timeframe.to_exchange_format(Exchange.GATE, MarketType.FUTURES),
            symbols=tickers,
        )

    def trades(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        tickers = self._normalize_symbols(symbol, symbols)

        wrapper = self._make_wrapper(self._adapter.trades_message, callback)
        return self._websocket_manager.trades(callback=wrapper, symbols=tickers)

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

    def futures_trades(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        tickers = self._normalize_symbols(symbol, symbols)

        wrapper = self._make_wrapper(self._adapter.futures_trades_message, callback)
        return self._websocket_manager.futures_trades(callback=wrapper, symbols=tickers)

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

    def futures_best_bid_ask(
        self,
        callback: CallbackType,
        symbol: str | None = None,
        symbols: Sequence[str] | None = None,
    ) -> Websocket:
        tickers = self._normalize_symbols(symbol, symbols)

        wrapper = self._make_wrapper(self._adapter.futures_best_bid_ask_message, callback)
        return self._websocket_manager.futures_book_ticker(callback=wrapper, symbols=tickers)

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

        tickers = self._normalize_symbols(symbol, symbols)

        wrapper = self._make_wrapper(self._adapter.futures_partial_book_depth_message, callback)
        return self._websocket_manager.futures_order_book(
            callback=wrapper,
            symbols=tickers,
            limit=str(limit),  # type: ignore[arg-type]
            interval="0",
        )
