"""
HTTP client for the Zero API.

Handles agent activation, intelligence sync, decision/trade reporting,
and heartbeat.
"""

import httpx


class ZeroNetwork:
    def __init__(self, token: str, api_base: str = "https://getzero.dev/api"):
        self.token = token
        self.api_base = api_base.rstrip("/")
        self._headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }

    def _client(self) -> httpx.AsyncClient:
        return httpx.AsyncClient(
            base_url=self.api_base,
            headers=self._headers,
            timeout=30.0,
        )

    async def activate(self, wallet: str) -> dict:
        """POST /api/agents/activate — activate agent with wallet."""
        async with self._client() as client:
            resp = await client.post("/agents/activate", json={"wallet_address": wallet})
            resp.raise_for_status()
            return resp.json()

    async def sync(self) -> dict:
        """GET /api/intelligence/sync — fetch latest collective intelligence."""
        async with self._client() as client:
            resp = await client.get("/intelligence/sync")
            resp.raise_for_status()
            return resp.json()

    async def report_decision(self, coin: str, direction: str,
                              action: str, regime: str) -> dict:
        """POST /api/agents/decision — report a trading decision."""
        async with self._client() as client:
            resp = await client.post("/agents/decision", json={
                "coin": coin,
                "direction": direction,
                "action": action,
                "regime": regime,
            })
            resp.raise_for_status()
            return resp.json()

    async def report_trade(self, coin: str, direction: str,
                           entry: float, exit_price: float,
                           pnl: float) -> dict:
        """POST /api/agents/trade — report a completed trade."""
        async with self._client() as client:
            resp = await client.post("/agents/trade", json={
                "coin": coin,
                "direction": direction,
                "entry_price": entry,
                "exit_price": exit_price,
                "pnl": pnl,
            })
            resp.raise_for_status()
            return resp.json()

    async def heartbeat(self, equity: float, positions: list[dict]) -> dict:
        """POST /api/agents/heartbeat — send heartbeat with current state."""
        async with self._client() as client:
            resp = await client.post("/agents/heartbeat", json={
                "equity": equity,
                "positions": positions,
            })
            resp.raise_for_status()
            return resp.json()
