"""HTTP client for the AAL API."""

from __future__ import annotations

from typing import Any

import httpx

from .errors import AALError


class HttpClient:
    """Async HTTP client with Bearer auth and error handling."""

    def __init__(self, base_url: str, api_key: str) -> None:
        self._base_url = base_url.rstrip("/")
        self._client = httpx.AsyncClient(
            base_url=self._base_url,
            headers={
                "Authorization": f"Bearer {api_key}",
            },
            timeout=30.0,
        )

    async def get(self, path: str) -> Any:
        return await self._request("GET", path)

    async def post(self, path: str, body: Any) -> Any:
        return await self._request("POST", path, json=body)

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

    async def _request(self, method: str, path: str, **kwargs: Any) -> Any:
        response = await self._client.request(method, path, **kwargs)
        if response.status_code >= 400:
            try:
                error_body = response.json()
                error_info = error_body.get("error", error_body)
            except Exception:
                error_info = {
                    "message": f"HTTP {response.status_code}",
                    "code": "UNKNOWN_ERROR",
                }
            raise AALError(
                message=error_info.get("message", f"HTTP {response.status_code}"),
                status=response.status_code,
                code=error_info.get("code", "UNKNOWN_ERROR"),
                request_id=error_info.get("requestId"),
            )
        return response.json()
