import unittest
from unittest.mock import patch
from analogai.deepthink.infrastructure.gateways.llm.llm_factory import LlmGatewayFactory
from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack
from analogai.deepthink.presentation.preprocessing.preprocessor import preprocess_text


class TestPreprocessorIntegration(unittest.TestCase):
    def setUp(self):
        self.real_gateway = LlmGatewayFactory.create_sentence_decomposer_and_transformer()
        self.patcher = patch.object(LlmGatewayFactory, 'create_sentence_decomposer_and_transformer', return_value=self.real_gateway)
        self.patcher.start()
    
    def tearDown(self):
        self.patcher.stop()

    def test_preprocessor_chain(self):
        input_text = "I am your creator"
        preprocessed = preprocess_text(input_text, PreviousMessagesStack())
        self.assertIsNotNone(preprocessed)
        self.assertIsInstance(preprocessed, str)

    def test_preprocessor_with_pronouns(self):
        input_text = "You are my friend"
        preprocessed = preprocess_text(input_text, PreviousMessagesStack())
        self.assertIsNotNone(preprocessed)
        self.assertIsInstance(preprocessed, str)

    def test_preprocessor_with_causal(self):
        input_text = "If it rains, I will stay home"
        preprocessed = preprocess_text(input_text, PreviousMessagesStack())
        self.assertIsNotNone(preprocessed)
        self.assertIsInstance(preprocessed, str)

    def test_pronoun_resolution_in_conversation(self):
        store = PreviousMessagesStack()
        first_message = "john is mortal"
        second_message = "he is philosopher"
        
        preprocess_text(first_message, store)
        result = preprocess_text(second_message, store)
        
        self.assertIn("john", result.lower())
        result_words = result.lower().split()
        self.assertNotIn("he", result_words)

    def test_previous_messages_stack_persists_across_calls(self):
        stack = PreviousMessagesStack()
        first_message = "socrates is human"
        second_message = "socrates sells iphone 12"
        
        preprocess_text(first_message, stack)
        history_after_first = list(stack.get_history())
        self.assertEqual(len(history_after_first), 1)
        
        preprocess_text(second_message, stack)
        history_after_second = list(stack.get_history())
        self.assertEqual(len(history_after_second), 2)


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

