"""HTTP client for the mem0-backed memory service."""

import logging
from typing import Optional, List, Any

import aiohttp

from .exceptions import APIException

logger = logging.getLogger(__name__)


class MemoryV2Client:
    """HTTP client for the mem0-backed memory service.

    Provides memory ingestion and semantic search via the memory service proxy.
    """

    def __init__(self, base_url: str):
        self.base_url = base_url.rstrip("/")
        self._session: Optional[aiohttp.ClientSession] = None

    async def _get_session(self) -> aiohttp.ClientSession:
        if self._session is None or self._session.closed:
            timeout = aiohttp.ClientTimeout(total=30.0)
            self._session = aiohttp.ClientSession(timeout=timeout)
        return self._session

    async def close(self):
        if self._session and not self._session.closed:
            await self._session.close()

    async def ingest(
        self,
        user_id: str,
        content: str,
        role: str = "user",
        conversation_id: Optional[str] = None,
    ) -> Any:
        """Ingest a message into mem0 memory.

        Args:
            user_id: User identifier
            content: Message content to ingest
            role: Message role ('user', 'assistant', or 'system')
            conversation_id: Optional conversation identifier

        Returns:
            mem0 ingestion result
        """
        url = f"{self.base_url}/ingest"
        payload: dict = {
            "user_id": user_id,
            "role": role,
            "content": content,
        }
        if conversation_id:
            payload["conversation_id"] = conversation_id

        session = await self._get_session()
        try:
            async with session.post(url, json=payload) as response:
                if response.status >= 400:
                    error_text = await response.text()
                    raise APIException(
                        f"Memory V2 ingest failed: {response.status} - {error_text}"
                    )
                return await response.json()
        except aiohttp.ClientError as e:
            raise APIException(f"Memory V2 ingest failed: {e}")

    async def search(self, query: str, user_id: str) -> List[Any]:
        """Search mem0 memories for a user.

        Args:
            query: Semantic search query
            user_id: User identifier

        Returns:
            List of mem0 search results
        """
        url = f"{self.base_url}/search"
        payload = {"query": query, "user_id": user_id}

        session = await self._get_session()
        try:
            async with session.post(url, json=payload) as response:
                if response.status >= 400:
                    error_text = await response.text()
                    raise APIException(
                        f"Memory V2 search failed: {response.status} - {error_text}"
                    )
                return await response.json()
        except aiohttp.ClientError as e:
            raise APIException(f"Memory V2 search failed: {e}")
