# -*- 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

from ccxt.base.exchange import Exchange
from ccxt.abstract.kifpoolme import ImplicitAPI
import math
from ccxt.base.types import Any, Int, Market, Strings, Ticker, Tickers
from typing import List


class kifpoolme(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(kifpoolme, self).describe(), {
            'id': 'kifpoolme',
            'name': 'Kifpool',
            'countries': ['IR'],
            'rateLimit': 1000,
            'version': '1',
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelAllOrders': False,
                'cancelOrder': False,
                'cancelOrders': False,
                'createDepositAddress': False,
                'createOrder': False,
                'createStopLimitOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'editOrder': False,
                'fetchBalance': False,
                'fetchBorrowInterest': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchClosedOrders': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': False,
                'fetchDepositAddress': False,
                'fetchDeposits': False,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchL2OrderBook': False,
                'fetchL3OrderBook': False,
                'fetchLedger': False,
                'fetchLedgerEntry': False,
                'fetchLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': False,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': False,
                'fetchOrder': False,
                'fetchOrderBook': False,
                'fetchOrders': False,
                'fetchOrderTrades': 'emulated',
                'fetchPositions': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': False,
                'fetchTrades': False,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchWithdrawals': False,
                'setLeverage': False,
                'setMarginMode': False,
                'transfer': False,
                'withdraw': False,
            },
            'comment': 'This comment is optional',
            'urls': {
                'logo': 'https://cdn.arz.digital/cr-odin/img/exchanges/kifpoolme/64x64.png',
                'api': {
                    'public': 'https://api.kifpool.app',
                },
                'www': 'https://kifpool.me/',
                'doc': [
                    'https://kifpool.me/',
                ],
            },
            'timeframes': {
                '1m': '1m',
                '5m': '5m',
                '15m': '15m',
                '30m': '30m',
                '1h': '1h',
                '4h': '4h',
                '1d': '1d',
                '1w': '1w',
            },
            'api': {
                'public': {
                    'get': {
                        'api/spot/price': 1,
                        'api/spot/tickers/1m': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    def parse_market(self, market) -> Market:
        # {
        #     "symbol": "BTC",
        #     "faName": "بیت کوین",
        #     "name": "Bitcoin",
        #     "smallImage": "https://kifpool.me/uploads/coin-new-images/bitcoin.png",
        #     "price": 115430,
        #     "priceBuyIRT": 13043590000,
        #     "priceSellIRT": 13135934000,
        #     "volume": 1700068128.9919832,
        #     "priceChangePercent": 3.4799999999999995,
        #     "high": 115968.8,
        #     "low": 111145.4,
        #     "slug": "bitcoin-BTC"
        # }
        baseId = self.safe_string(market, 'symbol')
        quoteId = self.safe_string(market, 'quoteId', 'USDT')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        id = baseId + '/' + quoteId
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'spot',
            'spot': True,
            'margin': False,
            'swap': False,
            'future': False,
            'option': False,
            'active': True,
            'contract': False,
            'linear': None,
            'inverse': None,
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': None,
                'price': None,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': None,
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

    def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for kifpoolme
        https://api.kifpool.app/api/spot/price
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetApiSpotPrice()
        result = []
        # Response is an array of coin objects
        for i in range(0, len(response)):
            item = response[i]
            # Create markets for both USDT and IRT quotes
            quotes = ['USDT', 'IRT']
            for j in range(0, len(quotes)):
                quoteId = quotes[j]
                marketData = self.extend(item, {
                    'quoteId': quoteId,
                })
                market = self.parse_market(marketData)
                result.append(market)
        return result

    def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        https://api.kifpool.app/api/spot/price
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        # Extract base symbols from the requested symbols
        symbolsParam = None
        if symbols is not None and len(symbols) > 0:
            baseSymbols = []
            for i in range(0, len(symbols)):
                market = self.market(symbols[i])
                if not (market['baseId'] in baseSymbols):
                    baseSymbols.append(market['baseId'])
            symbolsParam = ','.join(baseSymbols)
        request = {}
        if symbolsParam is not None:
            request['symbol'] = symbolsParam
        response = self.publicGetApiSpotPrice(self.extend(request))
        result = {}
        for i in range(0, len(response)):
            item = response[i]
            baseId = self.safe_string(item, 'symbol')
            # Create tickers for both USDT and IRT quotes
            quotes = ['USDT', 'IRT']
            for j in range(0, len(quotes)):
                quoteId = quotes[j]
                base = self.safe_currency_code(baseId)
                quote = self.safe_currency_code(quoteId)
                symbol = base + '/' + quote
                ticker = self.extend(item, {
                    'quoteId': quoteId,
                    'marketId': baseId + '/' + quoteId,
                })
                result[symbol] = self.parse_ticker(ticker)
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    def fetch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        https://api.kifpool.app/api/spot/price
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        ticker = self.fetch_tickers([symbol], params)
        return ticker[symbol]

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     "symbol": "BTC",
        #     "faName": "بیت کوین",
        #     "name": "Bitcoin",
        #     "smallImage": "https://kifpool.me/uploads/coin-new-images/bitcoin.png",
        #     "price": 115430,               # USDT price
        #     "priceBuyIRT": 13043590000,    # IRT buy price
        #     "priceSellIRT": 13135934000,   # IRT sell price
        #     "volume": 1700068128.9919832,
        #     "priceChangePercent": 3.48,
        #     "high": 115968.8,
        #     "low": 111145.4,
        #     "slug": "bitcoin-BTC",
        #     "quoteId": "USDT" or "IRT"
        # }
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'marketId')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        quoteId = self.safe_string(ticker, 'quoteId', 'USDT')
        last = None
        bid = None
        ask = None
        if quoteId == 'IRT':
            # For IRT: priceSellIRT is the sell price(bid), priceBuyIRT is the buy price(ask)
            bid = self.safe_number(ticker, 'priceSellIRT')
            ask = self.safe_number(ticker, 'priceBuyIRT')
            last = ask
        else:
            # For USDT: price is in USDT
            price = self.safe_number(ticker, 'price')
            last = price
            bid = price
            ask = price
        high = self.safe_number(ticker, 'high')
        low = self.safe_number(ticker, 'low')
        percentage = self.safe_number(ticker, 'priceChangePercent')
        baseVolume = self.safe_number(ticker, 'volume')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': high,
            'low': low,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': None,
            'info': ticker,
        }, market)

    def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        https://api.kifpool.app/api/spot/tickers/1m
        :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
        """
        self.load_markets()
        market = self.market(symbol)
        endTime = Date.now()
        request = {
            'symbol': market['baseId'],
            'currency': market['quoteId'],
            'fromTs': int(math.floor((endTime / 1000)) - (24 * 60 * 60)),
            'toTs': int(math.floor(endTime / 1000)),
        }
        if since is not None:
            request['fromTs'] = int(math.floor(since / 1000))
        if limit is not None:
            request['limit'] = limit
        response = self.publicGetApiSpotTickers1m(request)
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        # {
        #     "data_captured_datetime": 1760169720,
        #     "open": 110419.9,
        #     "high": 110468.4,
        #     "low": 110330.7,
        #     "close": 110330.7,
        #     "volume": 3356941116.288925,
        #     "changePercentage": -0.0808
        # }
        return [
            self.safe_timestamp(ohlcv, 'data_captured_datetime'),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        query = self.omit(params, self.extract_params(path))
        url = self.urls['api']['public'] + '/' + path
        if query:
            url += '?' + self.urlencode(query)
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
