# -*- 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.async_support.base.exchange import Exchange
from ccxt.abstract.kcex import ImplicitAPI
from ccxt.base.types import Any, Market, Strings, Ticker, Tickers
from typing import List


class kcex(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(kcex, self).describe(), {
            'id': 'kcex',
            'name': 'Kcex',
            'countries': ['SC'],
            'rateLimit': 1000,
            'version': '1',
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': True,
                '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': True,
                '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/kcex/64x64.png',
                'api': {
                    'public': 'https://www.kcex.com/spot/api',
                },
                'www': 'https://www.kcex.com',
                'doc': [
                    'https://www.kcex.com',
                ],
            },
            'timeframes': {
                '1m': '1',
                '1h': '60',
                '3h': '180',
                '6h': '360',
                '12h': '720',
                '1d': '1D',
            },
            'api': {
                'public': {
                    'get': {
                        'market-2/spot/market/v2/web/symbols': 1,
                        'market-2/spot/market/v2/web/tickers': 1,
                        'market-2/spot/market/v2/web/symbol/ticker': 1,
                    },
                },
            },
            # 'fees': {
            #     'trading': {
            #         'tierBased': False,
            #         'percentage': True,
            #         'maker': self.parse_number('0.001'),
            #         'taker': self.parse_number('0.001'),
            #     },
            # },
        })

    async def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for kcex
        https://api-docs.kcex.ir/#be8d9c51a2
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetMarket2SpotMarketV2WebSymbols(params)
        data = self.safe_dict(response, 'data')
        USDTmarketList = self.safe_list(data, 'USDT')
        USDCmarketList = self.safe_list(data, 'USDC')
        marketList = self.array_concat(USDTmarketList, USDCmarketList)
        result = []
        for i in range(0, len(marketList)):
            market = self.parse_market(marketList[i])
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        #         {
        # id: "e16a2713c7a44bac9d1d4ef98467e75b",
        # mcd: "20f24a571c8544c0b1362794b1804456",
        # mnm: "USDT",
        # cd: "18f40e5428054a4b9c69ddb0cce486f3",
        # vn: "AP",
        # fn: "AMERICA PARTY",
        # srt: 322,
        # sts: 1,
        # in: "F20250607111147267iXgSHIElFbibIQ",
        # fot: 1749247200000,
        # ot: 1749267000000,
        # cp: [
        # "common_section_meme",
        # "common_section_solana"
        # ],
        # ps: 7,
        # qs: 2,
        # cdm: 1
        # }
        id = self.safe_string(market, 'id')
        baseId = self.safe_string(market, 'vn')
        quoteId = self.safe_string(market, 'mnm')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        baseId = baseId.lower()
        quoteId = quoteId.lower()
        return {
            'id': base + '/' + quote,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': id,
            '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,
        }

    async 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-docs.kcex.ir/#be8d9c51a2
        :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>`
        """
        await self.load_markets()
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        response = await self.publicGetMarket2SpotMarketV2WebTickers(params)
        tickers = self.safe_list(response, 'data')
        timestamp = self.safe_integer(response, 'timestamp')
        result = {}
        idToMarket = {}
        marketList = list(self.markets.values())
        for i in range(0, len(marketList)):
            market = marketList[i]
            idToMarket[market['settleId']] = market
        for i in range(0, len(tickers)):
            ticker = tickers[i]
            id = self.safe_string(ticker, 'id')
            market = self.safe_value(idToMarket, id)
            ticker['timestamp'] = timestamp
            if market is not None:
                parsedTicker = self.parse_ticker(ticker, market)
                symbol = parsedTicker['symbol']
                result[symbol] = parsedTicker
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    async 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-docs.kcex.ir/#be8d9c51a2
        :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>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['base'] + '_' + market['quote'],
        }
        response = await self.publicGetMarket2SpotMarketV2WebSymbolTicker(request)
        tickerdata = self.safe_dict(response, 'data')
        ticker = self.parse_ticker(tickerdata, market)
        return ticker

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        #         {
        # id: "e16a2713c7a44bac9d1d4ef98467e75b",
        # r8: "-0.0261",
        # tzr: "-0.0261",
        # c: "0.0004552",
        # h: "0.0005745",
        # l: "0.0004552",
        # a: "136545.934217",
        # q: "281221205.24",
        # o: "0.0004674",
        # ot: 1749247200000
        # }
        symbol = market['symbol']
        high = self.safe_float(ticker, 'h', 0)
        low = self.safe_float(ticker, 'l', 0)
        open = self.safe_float(ticker, 'o', 0)
        last = self.safe_float(ticker, 'c', 0)
        quoteVolume = self.safe_float(ticker, 'a', 0)
        baseVolume = self.safe_float(ticker, 'q', 0)
        timestamp = self.safe_integer(ticker, 'timestamp', 0)
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': high,
            'low': low,
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    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 path == 'market-2/spot/market/v2/web/symbol/ticker':
            url = url + '?' + self.urlencode(query)
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
