from __future__ import annotations

from typing import Any

import httpx


class ApiClient:
    def __init__(self, server_url: str, groups_header: str, peer_id: str) -> None:
        self._base_url = server_url.rstrip("/")
        self._client = httpx.AsyncClient(
            timeout=10,
            headers={
                "X-Peer-Id": peer_id,
                "X-Groups": groups_header,
            },
        )

    async def get_messages(
        self, group_id: str, since_seq: int = 0, limit: int = 100
    ) -> list[dict[str, Any]]:
        resp = await self._client.get(
            f"{self._base_url}/auth/groups/{group_id}/messages",
            params={"since_seq": since_seq, "limit": limit},
        )
        resp.raise_for_status()
        return resp.json()["messages"]

    async def get_peers(self, group_id: str) -> list[dict[str, Any]]:
        resp = await self._client.get(
            f"{self._base_url}/auth/groups/{group_id}/peers",
        )
        resp.raise_for_status()
        return resp.json()["peers"]

    async def close(self) -> None:
        await self._client.aclose()
