import unittest

from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack
from analogai.deepthink.tests.functional.storage_cleaner import cleanup_storages
from analogai.deepthink.thinker import DeepThinker


class TestThinkerPreviousMessageStackIntegration(unittest.TestCase):
    def setUp(self):
        cleanup_storages()
        self._deepthink = DeepThinker()

    def tearDown(self):
        cleanup_storages()

    def test_conversation_saved_per_user_after_think(self):
        user_id = "user-a"
        agent_id = "agent-1"
        stack = PreviousMessagesStack()
        self._deepthink.deepthink("socrates is human", user_id=user_id, agent_id=agent_id, previous_messages_stack=stack)
        history = list(stack.get_history())
        self.assertEqual(len(history), 1)
        self.assertIn("socrates", history[0].lower())
        self.assertIn("human", history[0].lower())

    def test_conversation_adapted_to_stack_and_used_for_pronoun_resolution(self):
        user_id = "user-b"
        agent_id = "agent-1"
        stack = PreviousMessagesStack()
        self._deepthink.deepthink("john is mortal", user_id=user_id, agent_id=agent_id, previous_messages_stack=stack)
        result = self._deepthink.deepthink("he is philosopher", user_id=user_id, agent_id=agent_id, previous_messages_stack=stack)
        self.assertIsNotNone(result)
        self.assertIn("john", result.lower())
        self.assertNotIn(" he ", f" {result.lower()} ")
        history = list(stack.get_history())
        self.assertEqual(len(history), 2)

    def test_conversations_isolated_per_user(self):
        stack_user1 = PreviousMessagesStack()
        stack_user2 = PreviousMessagesStack()
        self._deepthink.deepthink("alice likes apples", user_id="user-1", agent_id="agent-1", previous_messages_stack=stack_user1)
        self._deepthink.deepthink("bob likes oranges", user_id="user-2", agent_id="agent-1", previous_messages_stack=stack_user2)
        history_user1 = list(stack_user1.get_history())
        history_user2 = list(stack_user2.get_history())
        self.assertEqual(history_user1, ["alice likes apples"])
        self.assertEqual(history_user2, ["bob likes oranges"])

    def test_conversation_adapted_to_stack_returns_persisted_history(self):
        user_id = "user-c"
        agent_id = "agent-1"
        stack = PreviousMessagesStack()
        self._deepthink.deepthink("maria reads books", user_id=user_id, agent_id=agent_id, previous_messages_stack=stack)
        history = list(stack.get_history())
        self.assertGreater(len(history), 0)
        self.assertIn("maria reads books", history)


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