"""Client for the Purple Flea Wallet API (/api/v1/wallet/)."""

from __future__ import annotations

from typing import Any

from .client import PurpleFleaClient


class WalletClient:
    """High-level wrapper around the Purple Flea Wallet service.

    Handles deposits, withdrawals, balance queries, transaction history,
    and crypto address management. Routes live under ``/api/v1/wallet/``.
    """

    PREFIX = "/api/v1/wallet"
    DEFAULT_BASE_URL = "http://80.78.27.26:3000"

    def __init__(
        self,
        api_key: str,
        base_url: str | None = None,
        timeout: float = 30.0,
    ) -> None:
        self._http = PurpleFleaClient(
            api_key,
            base_url=base_url or self.DEFAULT_BASE_URL,
            timeout=timeout,
        )

    def _path(self, route: str) -> str:
        return f"{self.PREFIX}/{route.lstrip('/')}"

    # -- balance & info -------------------------------------------------------

    def get_balance(self) -> dict[str, Any]:
        """Get current wallet balance across all currencies."""
        return self._http.get(self.PREFIX)

    def get_address(self, currency: str) -> dict[str, Any]:
        """Get the deposit address for a given currency (e.g. ``"BTC"``, ``"ETH"``)."""
        return self._http.get(self._path(f"address/{currency}"))

    # -- deposits -------------------------------------------------------------

    def deposit(self, amount: float, currency: str = "USDC", **extra: Any) -> dict[str, Any]:
        """Initiate a deposit into the wallet.

        Parameters
        ----------
        amount:
            Amount to deposit.
        currency:
            Currency code (default ``"USDC"``).
        """
        return self._http.post(self._path("deposit"), amount=amount, currency=currency, **extra)

    def get_deposit(self, deposit_id: str) -> dict[str, Any]:
        """Get the status of a specific deposit."""
        return self._http.get(self._path(f"deposits/{deposit_id}"))

    def list_deposits(self, **filters: Any) -> dict[str, Any]:
        """List all deposits, optionally filtered by status or currency."""
        return self._http.get(self._path("deposits"), **filters)

    # -- withdrawals ----------------------------------------------------------

    def withdraw(
        self,
        amount: float,
        address: str,
        currency: str = "USDC",
        **extra: Any,
    ) -> dict[str, Any]:
        """Withdraw funds to an external address.

        Parameters
        ----------
        amount:
            Amount to withdraw.
        address:
            Destination wallet address.
        currency:
            Currency code (default ``"USDC"``).
        """
        return self._http.post(
            self._path("withdraw"),
            amount=amount,
            address=address,
            currency=currency,
            **extra,
        )

    def get_withdrawal(self, withdrawal_id: str) -> dict[str, Any]:
        """Get the status of a specific withdrawal."""
        return self._http.get(self._path(f"withdrawals/{withdrawal_id}"))

    def list_withdrawals(self, **filters: Any) -> dict[str, Any]:
        """List all withdrawals, optionally filtered by status or currency."""
        return self._http.get(self._path("withdrawals"), **filters)

    # -- transaction history --------------------------------------------------

    def list_transactions(self, limit: int = 50, **filters: Any) -> dict[str, Any]:
        """List all wallet transactions (deposits, withdrawals, game credits).

        Parameters
        ----------
        limit:
            Maximum number of transactions to return (default 50).
        """
        return self._http.get(self._path("transactions"), limit=limit, **filters)

    def get_transaction(self, transaction_id: str) -> dict[str, Any]:
        """Get details for a specific transaction."""
        return self._http.get(self._path(f"transactions/{transaction_id}"))

    # -- internal transfers ---------------------------------------------------

    def transfer(
        self,
        to_account: str,
        amount: float,
        currency: str = "USDC",
        **extra: Any,
    ) -> dict[str, Any]:
        """Transfer funds to another Purple Flea account.

        Parameters
        ----------
        to_account:
            Recipient username or account ID.
        amount:
            Amount to transfer.
        currency:
            Currency code (default ``"USDC"``).
        """
        return self._http.post(
            self._path("transfer"),
            to_account=to_account,
            amount=amount,
            currency=currency,
            **extra,
        )

    # -- lifecycle ------------------------------------------------------------

    def close(self) -> None:
        self._http.close()

    def __enter__(self) -> WalletClient:
        return self

    def __exit__(self, *args: object) -> None:
        self.close()
