"""HTTP client wrapping the Amrood REST API.

Handles both agent-key auth and session-cookie auth depending
on the current AuthState.
"""

from __future__ import annotations

import os

import httpx

from amrood_mcp.auth import AuthState


class AmroodAPI:
    """Async HTTP client for the Amrood API."""

    def __init__(self, auth: AuthState):
        self._auth = auth
        self._base = os.environ.get("AMROOD_BASE_URL", "https://amrood.io").rstrip("/")
        self._client: httpx.AsyncClient | None = None

    async def _get_client(self) -> httpx.AsyncClient:
        if self._client is None or self._client.is_closed:
            self._client = httpx.AsyncClient(base_url=self._base, timeout=30.0)
        return self._client

    def _headers(self, use_session: bool = False) -> dict[str, str]:
        headers: dict[str, str] = {"Content-Type": "application/json"}
        if use_session and self._auth.session_token:
            headers["Cookie"] = f"amrood_session={self._auth.session_token}"
        elif self._auth.agent_key:
            headers["x-agent-key"] = self._auth.agent_key
        return headers

    async def get(self, path: str, params: dict | None = None, use_session: bool = False) -> dict:
        client = await self._get_client()
        resp = await client.get(path, headers=self._headers(use_session), params=params)
        resp.raise_for_status()
        return resp.json()

    async def post(self, path: str, json: dict | None = None, use_session: bool = False) -> httpx.Response:
        """POST and return the full Response (caller may need headers/cookies)."""
        client = await self._get_client()
        resp = await client.post(path, headers=self._headers(use_session), json=json or {})
        return resp

    async def close(self):
        if self._client and not self._client.is_closed:
            await self._client.close()
