from typing import Any, Dict


class Payouts:
    """Initiate and track payouts."""

    def __init__(self, client):
        self._client = client

    def create(
        self,
        amount: str,
        destination_address: str,
        currency: str = "USDT_TRC20",
        chain: str = "TRON",
        external_ref: str = None,
        metadata: Dict[str, Any] = None,
        idempotency_key: str = None,
    ) -> dict:
        """
        Initiate a payout.

        Args:
            amount: Amount in USDT (minimum 20 USDT), e.g. "100"
            destination_address: TRON destination address
            currency: Currency (default: USDT_TRC20)
            chain: Chain (default: TRON)
            external_ref: Your internal reference ID
            metadata: Arbitrary metadata
            idempotency_key: Unique key to prevent duplicate requests

        Returns:
            Dict with transactionId, status, processingFee, requiresManualApproval, etc.
        """
        body = {
            "amount": amount,
            "destinationAddress": destination_address,
            "currency": currency,
            "chain": chain,
        }
        if external_ref is not None:
            body["externalRef"] = external_ref
        if metadata is not None:
            body["metadata"] = metadata

        res = self._client.post("/payout", json=body, idempotency_key=idempotency_key)
        return res["data"]

    def get(self, payout_id: str) -> dict:
        """Get a payout by ID."""
        res = self._client.get(f"/payout/{payout_id}")
        return res["data"]

    def estimate(self, amount, currency=None, chain=None, destination_address=None):
        """
        Estimate payout fees and processing time.

        Args:
            amount: Amount in USDT
            currency: Currency (e.g. "USDT_TRC20")
            chain: Chain (e.g. "TRON")
            destination_address: Destination address

        Returns:
            Dict with fee estimate details.
        """
        body = {"amount": amount}
        if currency:
            body["currency"] = currency
        if chain:
            body["chain"] = chain
        if destination_address:
            body["destinationAddress"] = destination_address
        res = self._client.request("POST", "/payout/estimate", json=body)
        return res["data"]

    def list(
        self,
        page: int = None,
        limit: int = None,
        status=None,
        cursor: str = None,
        sort: str = None,
        from_date: str = None,
        to_date: str = None,
    ) -> dict:
        """
        List payouts with optional filters.

        Args:
            status: Filter by status (e.g. "CONFIRMED", "PROCESSING")
            cursor: Cursor for pagination
            sort: Sort order (e.g. "createdAt:desc")
            from_date: Start date (ISO 8601)
            to_date: End date (ISO 8601)

        Returns:
            Dict with "items" (list) and "total" (int).
        """
        status_value = ",".join(status) if isinstance(status, list) else status
        params = {"page": page, "limit": limit, "status": status_value}
        if cursor:
            params["cursor"] = cursor
        if sort:
            params["sort"] = sort
        if from_date:
            params["from"] = from_date
        if to_date:
            params["to"] = to_date
        res = self._client.get("/payout", params=params)
        return res["data"]
