import unittest
import uuid

from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack
from analogai.deepthink.tests.e2e.base_deepthink_e2e_test import BaseThinkerE2ETest


class TestMultiUserThinkerE2E(BaseThinkerE2ETest):
    def setUp(self):
        super().setUp()
        self._user1_id = str(uuid.uuid4())
        self._user2_id = str(uuid.uuid4())
        self._agent1_id = str(uuid.uuid4())
        self._agent2_id = str(uuid.uuid4())

    def _think_user1_agent1(self, message: str):
        return self._deepthink.deepthink(
            message,
            user_id=self._user1_id,
            agent_id=self._agent1_id,
            previous_messages_stack=PreviousMessagesStack(),
        )

    def _think_user2_agent1(self, message: str):
        return self._deepthink.deepthink(
            message,
            user_id=self._user2_id,
            agent_id=self._agent1_id,
            previous_messages_stack=PreviousMessagesStack(),
        )

    def _think_user1_agent2(self, message: str):
        return self._deepthink.deepthink(
            message,
            user_id=self._user1_id,
            agent_id=self._agent2_id,
            previous_messages_stack=PreviousMessagesStack(),
        )

    def test_knowledge_persists_across_different_users_same_agent(self):
        self._think_user1_agent1("socrates is human")
        response = self._think_user2_agent1("is socrates human?")
        self.assertIsNotNone(response)
        message_text = (response or "").lower()
        self.assertTrue(
            "socrates" in message_text or "human" in message_text,
            f"Knowledge should persist across users with same agent. Got: {message_text[:200]}",
        )

    def test_user_isolation(self):
        self._think_user1_agent1("I like apples")
        response = self._think_user2_agent1("What do I like?")
        self.assertIsNone(response)

    def test_agent_knowledge_isolation(self):
        self._think_user1_agent1("Philosophy is interesting")
        response = self._think_user1_agent2("What is interesting?")
        self.assertIsNone(response)

    def test_multi_agent_conversation_flow(self):
        response1 = self._think_user1_agent1("Hello, I'm Alice")
        response2 = self._think_user2_agent1("Hello, I'm Bob")
        self.assertIsNotNone(response1)
        self.assertIsNotNone(response2)

    def test_concurrent_multi_user_multi_agent_scenario(self):
        self._think_user1_agent1("User 1 message to agent 1")
        self._think_user2_agent1("User 2 message to agent 2")
        self._think_user1_agent1("Another message from user 1")
        self._think_user2_agent1("Another message from user 2")


if __name__ == "__main__":
    unittest.main()
