"""Async HTTP client for Sentinel API with Ed25519 request signing.

Wraps httpx.AsyncClient and transparently adds X-Agent-Id, X-Timestamp,
and X-Signature headers to every authenticated request. Public endpoints
(like kill-switch status) skip signing.
"""

import json
import logging
import urllib.parse

import httpx

from sentinel_mcp.crypto import sign_request

logger = logging.getLogger(__name__)


class SentinelClient:
    """Sentinel API client with Ed25519 agent authentication."""

    def __init__(
        self,
        api_url: str,
        agent_id: str,
        public_key: str,
        private_key: str,
    ) -> None:
        self.api_url = api_url.rstrip("/")
        self.agent_id = agent_id
        self.public_key = public_key
        self.private_key = private_key
        self._http = httpx.AsyncClient(base_url=self.api_url, timeout=15.0)

    async def get(self, path: str, params: dict | None = None) -> dict | list:
        """Agent-authenticated GET request.

        Args:
            path: Relative path (e.g. "markets" or "agents/{id}").
                  Will be prefixed with /api/v1/ for signing.
            params: Optional query parameters dict.
        """
        full_path = f"/api/v1/{path}"
        if params:
            query_string = urllib.parse.urlencode(params)
            sign_path = f"{full_path}?{query_string}"
        else:
            sign_path = full_path

        auth = sign_request("GET", sign_path, None, self.private_key)
        headers = {
            "X-Agent-Id": self.agent_id,
            "X-Timestamp": auth["timestamp"],
            "X-Signature": auth["signature"],
        }
        logger.debug("GET %s", sign_path)
        resp = await self._http.get(path, params=params, headers=headers)
        resp.raise_for_status()
        return resp.json()

    async def post(self, path: str, body: dict) -> dict:
        """Agent-authenticated POST request.

        Args:
            path: Relative path (e.g. "trade").
            body: Request body as dict (will be JSON-serialized).
        """
        full_path = f"/api/v1/{path}"
        body_json = json.dumps(body)
        auth = sign_request("POST", full_path, body_json, self.private_key)
        headers = {
            "X-Agent-Id": self.agent_id,
            "X-Timestamp": auth["timestamp"],
            "X-Signature": auth["signature"],
            "Content-Type": "application/json",
        }
        logger.debug("POST %s", full_path)
        resp = await self._http.post(path, content=body_json, headers=headers)
        resp.raise_for_status()
        return resp.json()

    async def get_public(self, path: str) -> dict:
        """Unauthenticated GET request for public endpoints."""
        logger.debug("GET (public) %s", path)
        resp = await self._http.get(path)
        resp.raise_for_status()
        return resp.json()

    async def close(self) -> None:
        """Close the underlying HTTP client."""
        await self._http.aclose()
