import httpx
import pandas as pd

from ._http import fetch_parquet
from ._query import CacheableQuery


class ERC20TransfersQuery(CacheableQuery):
    def __init__(self, session: httpx.AsyncClient, base_url: str, tokens: list[str]):
        super().__init__(session, base_url, {"tokens": tokens})
        self._min_amount = None

    def min_amount(self, amount: float) -> "ERC20TransfersQuery":
        self._min_amount = amount
        return self

    async def fetch(self) -> pd.DataFrame:
        if self._min_amount is not None:
            self._body["min_amount"] = self._min_amount
            path = "/erc20_transfers/read/min"
        else:
            path = "/erc20_transfers/read"
        return await fetch_parquet(self._session, self._base_url + path, self._body)


class ERC20Namespace:
    def __init__(self, session: httpx.AsyncClient, base_url: str):
        self._session = session
        self._base_url = base_url

    def transfers(self, tokens: list[str]) -> ERC20TransfersQuery:
        return ERC20TransfersQuery(self._session, self._base_url, tokens)

    async def flush(self, network: str | None = None, token: str | None = None) -> None:
        body = {}
        if network is not None:
            body["network"] = network
        if token is not None:
            body["token"] = token
        await self._session.post(self._base_url + "/erc20_transfers/flush", json=body)
