from dataclasses import dataclass
from decimal import Decimal
from typing_extensions import Literal, NotRequired, TypedDict
from ..core import IndexerMixin, response_parser

class PerpetualMarket(TypedDict):
  clobPairId: str
  ticker: str
  status: Literal['ACTIVE', 'PAUSED', 'CANCEL_ONLY', 'POST_ONLY', 'INITIALIZING', 'FINAL_SETTLEMENT']
  oraclePrice: Decimal
  priceChange24H: Decimal
  volume24H: Decimal
  trades24H: int
  nextFundingRate: Decimal
  initialMarginFraction: Decimal
  maintenanceMarginFraction: Decimal
  openInterest: Decimal
  atomicResolution: int
  quantumConversionExponent: int
  tickSize: Decimal
  stepSize: Decimal
  stepBaseQuantums: int
  subticksPerTick: int
  marketType: Literal['CROSS', 'ISOLATED']
  openInterestLowerCap: NotRequired[Decimal | None]
  openInterestUpperCap: NotRequired[Decimal | None]
  baseOpenInterest: Decimal
  defaultFundingRate1H: NotRequired[Decimal | None]

class GetMarketsResponse(TypedDict):
  markets: dict[str, PerpetualMarket]

parse_response = response_parser(GetMarketsResponse)

@dataclass
class GetMarkets(IndexerMixin):
  async def get_markets(
    self,
    *,
    market: str | None = None,
    limit: int | None = None,
    validate: bool | None = None
  ) -> GetMarketsResponse:
    """
    Retrieve perpetual market metadata from the indexer. When `market` is provided, the request filters to a single market.

    - `market`: Specific market ticker to retrieve, for example `BTC-USD`.
    - `limit`: Maximum number of market entries to return.
    - `validate`: Whether to validate the response against the generated schema.

    > [Official API docs](https://docs.dydx.xyz/indexer-client/http#get-perpetual-markets)
    """
    params: dict[str, object] = {}
    if market is not None:
      params['market'] = market
    if limit is not None:
      params['limit'] = limit
    r = await self.request('GET', '/v4/perpetualMarkets', params=params)
    return parse_response(r, validate=self.validate(validate))

