"""Wallet resource — create, retrieve, fund, and list wallets."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, List, Optional

if TYPE_CHECKING:
    from wallgent.http import HttpClient


class WalletsResource:
    def __init__(self, http: HttpClient) -> None:
        self._http = http

    def create(self, *, name: str, agent_name: Optional[str] = None) -> Dict[str, Any]:
        body: Dict[str, Any] = {"name": name}
        if agent_name is not None:
            body["agentName"] = agent_name
        return self._http.request("POST", "/v1/wallets", body)

    def retrieve(self, wallet_id: str) -> Dict[str, Any]:
        return self._http.request("GET", f"/v1/wallets/{wallet_id}")

    def get_balance(self, wallet_id: str) -> Dict[str, Any]:
        return self._http.request("GET", f"/v1/wallets/{wallet_id}/balance")

    def fund(self, wallet_id: str, *, amount: float) -> Dict[str, Any]:
        return self._http.request("POST", f"/v1/wallets/{wallet_id}/fund", {"amount": amount})

    def list(self) -> List[Dict[str, Any]]:
        resp = self._http.request("GET", "/v1/wallets")
        return resp.get("data", []) if isinstance(resp, dict) else resp

    def list_transactions(
        self,
        wallet_id: str,
        *,
        limit: Optional[int] = None,
        cursor: Optional[str] = None,
    ) -> Dict[str, Any]:
        params = {}
        if limit is not None:
            params["limit"] = str(limit)
        if cursor is not None:
            params["cursor"] = cursor
        qs = "&".join(f"{k}={v}" for k, v in params.items())
        path = f"/v1/wallets/{wallet_id}/transactions{'?' + qs if qs else ''}"
        return self._http.request("GET", path)

    # ── Async variants ───────────────────────────────────────

    async def acreate(self, *, name: str, agent_name: Optional[str] = None) -> Dict[str, Any]:
        body: Dict[str, Any] = {"name": name}
        if agent_name is not None:
            body["agentName"] = agent_name
        return await self._http.arequest("POST", "/v1/wallets", body)

    async def aretrieve(self, wallet_id: str) -> Dict[str, Any]:
        return await self._http.arequest("GET", f"/v1/wallets/{wallet_id}")

    async def aget_balance(self, wallet_id: str) -> Dict[str, Any]:
        return await self._http.arequest("GET", f"/v1/wallets/{wallet_id}/balance")

    async def afund(self, wallet_id: str, *, amount: float) -> Dict[str, Any]:
        return await self._http.arequest("POST", f"/v1/wallets/{wallet_id}/fund", {"amount": amount})

    async def alist(self) -> List[Dict[str, Any]]:
        resp = await self._http.arequest("GET", "/v1/wallets")
        return resp.get("data", []) if isinstance(resp, dict) else resp

    async def alist_transactions(
        self,
        wallet_id: str,
        *,
        limit: Optional[int] = None,
        cursor: Optional[str] = None,
    ) -> Dict[str, Any]:
        params = {}
        if limit is not None:
            params["limit"] = str(limit)
        if cursor is not None:
            params["cursor"] = cursor
        qs = "&".join(f"{k}={v}" for k, v in params.items())
        path = f"/v1/wallets/{wallet_id}/transactions{'?' + qs if qs else ''}"
        return await self._http.arequest("GET", path)
