"""
Script to apply all improvements to the MangoIT chatbot
"""

import os
import sys
import asyncio
from crew.rag_crew import RAGCrew
from agents.response_generation_agent import ResponseGenerationAgent
from utils.agent_config import agent_config
from utils.integration_helper import integration_helper
from utils.logger import app_logger

async def main():
    """Apply all improvements to the MangoIT chatbot"""
    print("Applying improvements to the MangoIT chatbot...")
    
    # 1. Configure the agent name and company name
    print("\n1. Configuring agent identity...")
    agent_config.AGENT_NAME = "Mia"  # Change from "Sam" to "Mia"
    agent_config.COMPANY_NAME = "MangoIT Solutions"
    agent_config.SHORT_GREETINGS = True  # Use shorter greetings
    print(f"Agent name set to: {agent_config.AGENT_NAME}")
    print(f"Company name set to: {agent_config.COMPANY_NAME}")
    
    # 2. Initialize the RAG crew and response generation agent
    print("\n2. Initializing RAG crew and response generation agent...")
    rag_crew = RAGCrew(logger=app_logger)
    response_agent = ResponseGenerationAgent(logger=app_logger)
    
    # 3. Apply all improvements
    print("\n3. Applying all improvements...")
    integration_helper.integrate_all_improvements(
        crew_instance=rag_crew,
        response_agent=response_agent
    )
    
    # 4. Test the improvements with a sample query
    print("\n4. Testing the improvements with a sample query...")
    
    # Create a test conversation
    conversation_id = "test-improvements"
    
    # Test queries
    test_queries = [
        "Hello",
        "What technologies does MangoIT work with?",
        "How much does it cost to hire a developer?",
        "Can I schedule a meeting with your team?"
    ]
    
    # Process each query
    for i, query in enumerate(test_queries):
        print(f"\nQuery {i+1}: {query}")
        
        # Process the query
        response = await rag_crew.process_query(query, conversation_id)
        
        # Print the response
        print(f"Response: {response.get('response', 'No response generated')}")
        
        # Print sources if available
        sources = response.get("sources", [])
        if sources:
            print("\nSources:")
            for j, source in enumerate(sources[:3]):  # Show first 3 sources
                print(f"  {j+1}. {source.get('source', 'Unknown')} (relevance: {source.get('relevance', 0):.2f})")
            
            if len(sources) > 3:
                print(f"  ... and {len(sources) - 3} more")
    
    print("\nAll improvements have been applied and tested!")
    print("\nTo use these improvements in your application:")
    print("1. Import the integration_helper module")
    print("2. Call integration_helper.integrate_all_improvements() with your RAG crew and response agent")
    print("3. Update your main.py to use the optimized conversation memory")
    
    # Provide instructions for updating main.py
    print("\nAdd the following code to your main.py:")
    print("""
    # Import the optimized conversation memory
    from utils.optimized_conversation_memory import optimized_conversation_memory
    
    # Replace persistent_conversation_memory with optimized_conversation_memory
    # For example:
    # conversation_memory = optimized_conversation_memory
    """)

if __name__ == "__main__":
    asyncio.run(main())
