from analogai.foundation.common.logging.app_logger import app_logger
from analogai.deepthink.application.value_objects.user_agent import UserAgent
from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack
from analogai.deepthink.presentation.preprocessing.preprocessor_factory import create_preprocessor_chain

def preprocess_text(
    text: str,
    previous_messages_stack: PreviousMessagesStack,
    user_agent: UserAgent | None = None,
) -> str:
    if text is None:
        raise ValueError("Text cannot be None")
    app_logger.important(f"Starting preprocessing: {text}")
    original_text = text
    history_before = list(previous_messages_stack.get_history())
    # app_logger.info(f"Previous messages stack history before preprocessing: {history_before}")
    text = text.strip()
    
    user_id = user_agent.user_id if user_agent else None
    preprocessors = create_preprocessor_chain(previous_messages_stack, user_id=user_id)
    for i, preprocessor in enumerate(preprocessors, 1):
        text = preprocessor.process(text)
        app_logger.debug(f"Preprocessor step {i} - {preprocessor.__class__.__name__}: {text}")
    
    history_pairs = list(previous_messages_stack.get_history_pairs())
    if not history_pairs or history_pairs[-1] != ("user", original_text):
        previous_messages_stack.add_user(original_text)
    history_after = list(previous_messages_stack.get_history())
    # app_logger.info(f"Previous messages stack history after adding message: {history_after}")
    # app_logger.success(f"Finished preprocessing: {text}")
    return text

if __name__ == "__main__":
    text = [
            "there is cloud",
            "I'm your creator.",
            "Your voice sounds good.",
            "If there is a cloud, it might rain",
            
            "what do you think, would it rain?",
            "are you cute",
            "am I your creator?",
            "I mean bank, the river",
            "yes, that's right",
            "yes, I am sure",
            "yes",
            "no, socrates is not mortal",
            "what can you tell me about socrates?",
            "if there is cloud, it might rain",
            "Iphone X has USB-C port",
            "we have iphone 16"]
    from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack
    store = PreviousMessagesStack()
    for t in text:
        result = preprocess_text(t, store)
        print(result)

