from __future__ import annotations

"""Default in-process memory backend."""

from dataclasses import dataclass, field

from agentrspy.core import Memory, Message


@dataclass(slots=True)
class InMemoryMemory(Memory):
    """Memory backend that stores messages in process."""

    messages: list[Message] = field(default_factory=list)
    max_messages: int | None = None

    @classmethod
    def new(cls) -> "InMemoryMemory":
        return cls()

    @classmethod
    def with_max_messages(cls, max_messages: int) -> "InMemoryMemory":
        return cls(max_messages=max_messages)

    def _trim(self) -> None:
        if self.max_messages is None or len(self.messages) <= self.max_messages:
            return
        overflow = len(self.messages) - self.max_messages
        del self.messages[:overflow]

    async def store(self, key: str, value: Message) -> None:
        del key
        self.messages.append(value)
        self._trim()

    async def retrieve(self, query: str, limit: int) -> list[Message]:
        lowered = query.lower()
        return [
            message
            for message in self.messages
            if lowered in message.text_content().lower()
        ][:limit]

    async def history(self) -> list[Message]:
        return list(self.messages)

    async def clear(self) -> None:
        self.messages.clear()

    async def token_count(self) -> int:
        return sum(len(message.text_content()) // 4 for message in self.messages)
