"""Network resource — agent-to-agent payments via Wallgent addresses."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, List, Optional
from urllib.parse import quote

if TYPE_CHECKING:
    from wallgent.http import HttpClient


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

    def pay_agent(
        self,
        *,
        to_address: str,
        amount: str,
        description: Optional[str] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"toAddress": to_address, "amount": amount}
        if description is not None:
            body["description"] = description
        return self._http.request("POST", "/v1/network/pay", body)

    def search_directory(self, search: Optional[str] = None) -> List[Dict[str, Any]]:
        qs = f"?search={quote(search)}" if search else ""
        resp = self._http.request("GET", f"/v1/network/directory{qs}")
        return resp.get("data", []) if isinstance(resp, dict) else resp

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

    async def apay_agent(
        self,
        *,
        to_address: str,
        amount: str,
        description: Optional[str] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"toAddress": to_address, "amount": amount}
        if description is not None:
            body["description"] = description
        return await self._http.arequest("POST", "/v1/network/pay", body)

    async def asearch_directory(self, search: Optional[str] = None) -> List[Dict[str, Any]]:
        qs = f"?search={quote(search)}" if search else ""
        resp = await self._http.arequest("GET", f"/v1/network/directory{qs}")
        return resp.get("data", []) if isinstance(resp, dict) else resp
