from collections import deque
from typing import Sequence, TYPE_CHECKING

from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack

if TYPE_CHECKING:
    from analogai.foundation.extensions.conversation.services.conversation_service import ConversationService


class ConversationPreviousMessagesStackAdapter(PreviousMessagesStack):
    MAX_HISTORY_LIMIT = 5

    def __init__(
        self,
        conversation_service: "ConversationService",
        user_id: str,
        agent_id: str,
        history_limit: int = 5,
    ):
        super().__init__(maxlen=min(history_limit, self.MAX_HISTORY_LIMIT))
        self._conversation_service = conversation_service
        self._user_id = user_id
        self._agent_id = agent_id
        self._history_limit = min(history_limit, self.MAX_HISTORY_LIMIT)
        self._cached_conversation = None

    def add(self, text: str) -> None:
        pass

    def get_history(self) -> Sequence[str]:
        conversation = self._cached_conversation
        if conversation is None:
            conversation = self._conversation_service.get_latest_conversation(
                self._user_id, self._agent_id
            )
            self._cached_conversation = conversation
        if not conversation:
            return ()
        history = deque(maxlen=self.MAX_HISTORY_LIMIT)
        for turn in conversation.get_recent_turns(limit=self._history_limit):
            for part in (turn.user_message, turn.agent_response):
                if part and (cleaned := part.strip()):
                    history.append(cleaned)
        return tuple(history)

    def refresh(self) -> None:
        self._cached_conversation = None
