"""Tests for the AsyncCerebe client — async parity with sync client."""

from __future__ import annotations

import json

import pytest

from cerebe import AsyncCerebe
from cerebe._errors import AuthenticationError


@pytest.mark.anyio
class TestAsyncClient:
    async def test_requires_api_key(self) -> None:
        with pytest.raises(ValueError, match="API key is required"):
            AsyncCerebe(api_key="")

    async def test_sends_headers(self, httpx_mock) -> None:
        httpx_mock.add_response(json={"data": "ok", "meta": {}})
        async with AsyncCerebe(api_key="ck_async", project="proj_1", max_retries=0) as client:
            await client.request("GET", "/test")

        req = httpx_mock.get_request()
        assert req.headers["x-api-key"] == "ck_async"
        assert req.headers["x-cerebe-project"] == "proj_1"

    async def test_401_raises_auth_error(self, httpx_mock) -> None:
        httpx_mock.add_response(status_code=401, json={"error": {"message": "Bad key"}})
        async with AsyncCerebe(api_key="ck_test", max_retries=0) as client:
            with pytest.raises(AuthenticationError):
                await client.request("GET", "/test")

    async def test_retries_on_5xx(self, httpx_mock) -> None:
        httpx_mock.add_response(status_code=502, json={"error": {}})
        httpx_mock.add_response(json={"data": "recovered", "meta": {}})

        async with AsyncCerebe(api_key="ck_test", max_retries=1) as client:
            result = await client.request("GET", "/test")
        assert result.data == "recovered"


@pytest.mark.anyio
class TestAsyncMemory:
    async def test_add(self, httpx_mock) -> None:
        httpx_mock.add_response(json={"data": {"id": "mem_1"}, "meta": {}})
        async with AsyncCerebe(api_key="ck_test", max_retries=0) as client:
            await client.memory.add("test content", "sess_1", type="episodic")

        req = httpx_mock.get_request()
        data = json.loads(req.read())
        assert data["content"] == "test content"
        assert data["memory_type"] == "episodic"

    async def test_search(self, httpx_mock) -> None:
        httpx_mock.add_response(json={"data": {"memories": []}, "meta": {}})
        async with AsyncCerebe(api_key="ck_test", max_retries=0) as client:
            await client.memory.search("test", "sess_1")

        req = httpx_mock.get_request()
        data = json.loads(req.read())
        assert data["query"] == "test"


@pytest.mark.anyio
class TestAsyncAgent:
    async def test_ingest_trace(self, httpx_mock) -> None:
        httpx_mock.add_response(json={"data": {"id": "mem_1"}, "meta": {}})
        async with AsyncCerebe(api_key="ck_test", max_retries=0) as client:
            await client.agents.ingest_trace("tool called", "sess_1")

        req = httpx_mock.get_request()
        data = json.loads(req.read())
        assert data["memory_type"] == "execution_history"
