# -*- coding: utf-8 -*-

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

import ccxt.async_support
from ccxt.async_support.base.ws.cache import ArrayCache, ArrayCacheBySymbolById, ArrayCacheByTimestamp
from ccxt.base.types import Int, Market, Order, OrderBook, Str, Trade
from ccxt.async_support.base.ws.client import Client
from typing import List
from ccxt.base.errors import ExchangeError


class hyperliquid(ccxt.async_support.hyperliquid):

    def describe(self):
        return self.deep_extend(super(hyperliquid, self).describe(), {
            'has': {
                'ws': True,
                'watchBalance': False,
                'watchMyTrades': True,
                'watchOHLCV': True,
                'watchOrderBook': True,
                'watchOrders': True,
                'watchTicker': False,
                'watchTickers': False,
                'watchTrades': True,
                'watchPosition': False,
            },
            'urls': {
                'api': {
                    'ws': {
                        'public': 'wss://api.hyperliquid.xyz/ws',
                    },
                },
                'test': {
                    'ws': {
                        'public': 'wss://api.hyperliquid-testnet.xyz/ws',
                    },
                },
            },
            'options': {
            },
            'streaming': {
                'ping': self.ping,
                'keepAlive': 20000,
            },
            'exceptions': {
                'ws': {
                    'exact': {
                    },
                },
            },
        })

    async def watch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        market = self.market(symbol)
        symbol = market['symbol']
        messageHash = 'orderbook:' + symbol
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'subscribe',
            'subscription': {
                'type': 'l2Book',
                'coin': market['base'] if market['swap'] else market['id'],
            },
        }
        message = self.extend(request, params)
        orderbook = await self.watch(url, messageHash, message, messageHash)
        return orderbook.limit()

    def handle_order_book(self, client, message):
        #
        #     {
        #         "channel": "l2Book",
        #         "data": {
        #             "coin": "BTC",
        #             "time": 1710131872708,
        #             "levels": [
        #                 [
        #                     {
        #                         "px": "68674.0",
        #                         "sz": "0.97139",
        #                         "n": 4
        #                     }
        #                 ],
        #                 [
        #                     {
        #                         "px": "68675.0",
        #                         "sz": "0.04396",
        #                         "n": 1
        #                     }
        #                 ]
        #             ]
        #         }
        #     }
        #
        entry = self.safe_dict(message, 'data', {})
        coin = self.safe_string(entry, 'coin')
        marketId = self.coinToMarketId(coin)
        market = self.market(marketId)
        symbol = market['symbol']
        rawData = self.safe_list(entry, 'levels', [])
        data: dict = {
            'bids': self.safe_list(rawData, 0, []),
            'asks': self.safe_list(rawData, 1, []),
        }
        timestamp = self.safe_integer(entry, 'time')
        snapshot = self.parse_order_book(data, symbol, timestamp, 'bids', 'asks', 'px', 'sz')
        if not (symbol in self.orderbooks):
            ob = self.order_book(snapshot)
            self.orderbooks[symbol] = ob
        orderbook = self.orderbooks[symbol]
        orderbook.reset(snapshot)
        messageHash = 'orderbook:' + symbol
        client.resolve(orderbook, messageHash)

    async def watch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        watches information on multiple trades made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict[]: a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure
        """
        userAddress = None
        userAddress, params = self.handlePublicAddress('watchMyTrades', params)
        await self.load_markets()
        messageHash = 'myTrades'
        if symbol is not None:
            symbol = self.symbol(symbol)
            messageHash += ':' + symbol
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'subscribe',
            'subscription': {
                'type': 'userFills',
                'user': userAddress,
            },
        }
        message = self.extend(request, params)
        trades = await self.watch(url, messageHash, message, messageHash)
        if self.newUpdates:
            limit = trades.getLimit(symbol, limit)
        return self.filter_by_symbol_since_limit(trades, symbol, since, limit, True)

    def handle_my_trades(self, client: Client, message):
        #
        #     {
        #         "channel": "userFills",
        #         "data": {
        #             "isSnapshot": True,
        #             "user": "0x15f43d1f2dee81424afd891943262aa90f22cc2a",
        #             "fills": [
        #                 {
        #                     "coin": "BTC",
        #                     "px": "72528.0",
        #                     "sz": "0.11693",
        #                     "side": "A",
        #                     "time": 1710208712815,
        #                     "startPosition": "0.11693",
        #                     "dir": "Close Long",
        #                     "closedPnl": "-0.81851",
        #                     "hash": "0xc5adaf35f8402750c218040b0a7bc301130051521273b6f398b3caad3e1f3f5f",
        #                     "oid": 7484888874,
        #                     "crossed": True,
        #                     "fee": "2.968244",
        #                     "liquidationMarkPx": null,
        #                     "tid": 567547935839686,
        #                     "cloid": null
        #                 }
        #             ]
        #         }
        #     }
        #
        entry = self.safe_dict(message, 'data', {})
        if self.myTrades is None:
            limit = self.safe_integer(self.options, 'tradesLimit', 1000)
            self.myTrades = ArrayCacheBySymbolById(limit)
        trades = self.myTrades
        symbols: dict = {}
        data = self.safe_list(entry, 'fills', [])
        dataLength = len(data)
        if dataLength == 0:
            return
        for i in range(0, len(data)):
            rawTrade = data[i]
            parsed = self.parse_ws_trade(rawTrade)
            symbol = parsed['symbol']
            symbols[symbol] = True
            trades.append(parsed)
        keys = list(symbols.keys())
        for i in range(0, len(keys)):
            currentMessageHash = 'myTrades:' + keys[i]
            client.resolve(trades, currentMessageHash)
        # non-symbol specific
        messageHash = 'myTrades'
        client.resolve(trades, messageHash)

    async def watch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        watches information on multiple trades made in a market
        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure
        """
        await self.load_markets()
        market = self.market(symbol)
        symbol = market['symbol']
        messageHash = 'trade:' + symbol
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'subscribe',
            'subscription': {
                'type': 'trades',
                'coin': market['base'] if market['swap'] else market['id'],
            },
        }
        message = self.extend(request, params)
        trades = await self.watch(url, messageHash, message, messageHash)
        if self.newUpdates:
            limit = trades.getLimit(symbol, limit)
        return self.filter_by_since_limit(trades, since, limit, 'timestamp', True)

    def handle_trades(self, client: Client, message):
        #
        #     {
        #         "channel": "trades",
        #         "data": [
        #             {
        #                 "coin": "BTC",
        #                 "side": "A",
        #                 "px": "68517.0",
        #                 "sz": "0.005",
        #                 "time": 1710125266669,
        #                 "hash": "0xc872699f116e012186620407fc08a802015e0097c5cce74710697f7272e6e959",
        #                 "tid": 981894269203506
        #             }
        #         ]
        #     }
        #
        entry = self.safe_list(message, 'data', [])
        first = self.safe_dict(entry, 0, {})
        coin = self.safe_string(first, 'coin')
        marketId = self.coinToMarketId(coin)
        market = self.market(marketId)
        symbol = market['symbol']
        if not (symbol in self.trades):
            limit = self.safe_integer(self.options, 'tradesLimit', 1000)
            stored = ArrayCache(limit)
            self.trades[symbol] = stored
        trades = self.trades[symbol]
        for i in range(0, len(entry)):
            data = self.safe_dict(entry, i)
            trade = self.parse_ws_trade(data)
            trades.append(trade)
        messageHash = 'trade:' + symbol
        client.resolve(trades, messageHash)

    def parse_ws_trade(self, trade, market: Market = None) -> Trade:
        #
        # fetchMyTrades
        #
        #     {
        #         "coin": "BTC",
        #         "px": "72528.0",
        #         "sz": "0.11693",
        #         "side": "A",
        #         "time": 1710208712815,
        #         "startPosition": "0.11693",
        #         "dir": "Close Long",
        #         "closedPnl": "-0.81851",
        #         "hash": "0xc5adaf35f8402750c218040b0a7bc301130051521273b6f398b3caad3e1f3f5f",
        #         "oid": 7484888874,
        #         "crossed": True,
        #         "fee": "2.968244",
        #         "liquidationMarkPx": null,
        #         "tid": 567547935839686,
        #         "cloid": null
        #     }
        #
        # fetchTrades
        #
        #     {
        #         "coin": "BTC",
        #         "side": "A",
        #         "px": "68517.0",
        #         "sz": "0.005",
        #         "time": 1710125266669,
        #         "hash": "0xc872699f116e012186620407fc08a802015e0097c5cce74710697f7272e6e959",
        #         "tid": 981894269203506
        #     }
        #
        timestamp = self.safe_integer(trade, 'time')
        price = self.safe_string(trade, 'px')
        amount = self.safe_string(trade, 'sz')
        coin = self.safe_string(trade, 'coin')
        marketId = self.coinToMarketId(coin)
        market = self.safe_market(marketId, None)
        symbol = market['symbol']
        id = self.safe_string(trade, 'tid')
        side = self.safe_string(trade, 'side')
        if side is not None:
            side = 'sell' if (side == 'A') else 'buy'
        fee = self.safe_string(trade, 'fee')
        return self.safe_trade({
            'info': trade,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'id': id,
            'order': None,
            'type': None,
            'side': side,
            'takerOrMaker': None,
            'price': price,
            'amount': amount,
            'cost': None,
            'fee': {'cost': fee, 'currency': 'USDC'},
        }, market)

    async def watch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        watches historical candlestick data containing the open, high, low, close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        symbol = market['symbol']
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'subscribe',
            'subscription': {
                'type': 'candle',
                'coin': market['base'] if market['swap'] else market['id'],
                'interval': timeframe,
            },
        }
        messageHash = 'candles:' + timeframe + ':' + symbol
        message = self.extend(request, params)
        ohlcv = await self.watch(url, messageHash, message, messageHash)
        if self.newUpdates:
            limit = ohlcv.getLimit(symbol, limit)
        return self.filter_by_since_limit(ohlcv, since, limit, 0, True)

    def handle_ohlcv(self, client: Client, message):
        #
        #     {
        #         channel: 'candle',
        #         data: {
        #             t: 1710146280000,
        #             T: 1710146339999,
        #             s: 'BTC',
        #             i: '1m',
        #             o: '71400.0',
        #             c: '71411.0',
        #             h: '71422.0',
        #             l: '71389.0',
        #             v: '1.20407',
        #             n: 20
        #         }
        #     }
        #
        data = self.safe_dict(message, 'data', {})
        base = self.safe_string(data, 's')
        marketId = self.coinToMarketId(base)
        symbol = self.safe_symbol(marketId)
        timeframe = self.safe_string(data, 'i')
        if not (symbol in self.ohlcvs):
            self.ohlcvs[symbol] = {}
        if not (timeframe in self.ohlcvs[symbol]):
            limit = self.safe_integer(self.options, 'OHLCVLimit', 1000)
            stored = ArrayCacheByTimestamp(limit)
            self.ohlcvs[symbol][timeframe] = stored
        ohlcv = self.ohlcvs[symbol][timeframe]
        parsed = self.parse_ohlcv(data)
        ohlcv.append(parsed)
        messageHash = 'candles:' + timeframe + ':' + symbol
        client.resolve(ohlcv, messageHash)

    async def watch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        watches information on multiple orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.user]: user address, will default to self.walletAddress if not provided
        :returns dict[]: a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure
        """
        await self.load_markets()
        userAddress = None
        userAddress, params = self.handlePublicAddress('watchOrders', params)
        market = None
        messageHash = 'order'
        if symbol is not None:
            market = self.market(symbol)
            symbol = market['symbol']
            messageHash = messageHash + ':' + symbol
        url = self.urls['api']['ws']['public']
        request: dict = {
            'method': 'subscribe',
            'subscription': {
                'type': 'orderUpdates',
                'user': userAddress,
            },
        }
        message = self.extend(request, params)
        orders = await self.watch(url, messageHash, message, messageHash)
        if self.newUpdates:
            limit = orders.getLimit(symbol, limit)
        return self.filter_by_symbol_since_limit(orders, symbol, since, limit, True)

    def handle_order(self, client: Client, message):
        #
        #     {
        #         channel: 'orderUpdates',
        #         data: [
        #             {
        #                 order: {
        #                     coin: 'BTC',
        #                     side: 'B',
        #                     limitPx: '30000.0',
        #                     sz: '0.001',
        #                     oid: 7456484275,
        #                     timestamp: 1710163596492,
        #                     origSz: '0.001'
        #                 },
        #                 status: 'open',
        #                 statusTimestamp: 1710163596492
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(message, 'data', [])
        if self.orders is None:
            limit = self.safe_integer(self.options, 'ordersLimit', 1000)
            self.orders = ArrayCacheBySymbolById(limit)
        dataLength = len(data)
        if dataLength == 0:
            return
        stored = self.orders
        messageHash = 'order'
        marketSymbols: dict = {}
        for i in range(0, len(data)):
            rawOrder = data[i]
            order = self.parse_order(rawOrder)
            stored.append(order)
            symbol = self.safe_string(order, 'symbol')
            marketSymbols[symbol] = True
        keys = list(marketSymbols.keys())
        for i in range(0, len(keys)):
            symbol = keys[i]
            innerMessageHash = messageHash + ':' + symbol
            client.resolve(stored, innerMessageHash)
        client.resolve(stored, messageHash)

    def handle_error_message(self, client: Client, message):
        #
        #     {
        #         "channel": "error",
        #         "data": "Error parsing JSON into valid websocket request: {\"type\": \"allMids\"}"
        #     }
        #
        channel = self.safe_string(message, 'channel', '')
        ret_msg = self.safe_string(message, 'data', '')
        if channel == 'error':
            raise ExchangeError(self.id + ' ' + ret_msg)
        else:
            return False

    def handle_message(self, client: Client, message):
        if self.handle_error_message(client, message):
            return
        topic = self.safe_string(message, 'channel', '')
        methods: dict = {
            'pong': self.handle_pong,
            'trades': self.handle_trades,
            'l2Book': self.handle_order_book,
            'candle': self.handle_ohlcv,
            'orderUpdates': self.handle_order,
            'userFills': self.handle_my_trades,
        }
        exacMethod = self.safe_value(methods, topic)
        if exacMethod is not None:
            exacMethod(client, message)
            return
        keys = list(methods.keys())
        for i in range(0, len(keys)):
            key = keys[i]
            if topic.find(keys[i]) >= 0:
                method = methods[key]
                method(client, message)
                return

    def ping(self, client):
        return {
            'method': 'ping',
        }

    def handle_pong(self, client: Client, message):
        #
        #   {
        #       "channel": "pong"
        #   }
        #
        client.lastPong = self.safe_integer(message, 'pong')
        return message
