"""
Integration script to apply all improvements to the MangoIT chatbot
"""

import os
import sys
import asyncio
from typing import Dict, Any, Optional

# Import the components we want to integrate
from utils.optimized_conversation_memory import optimized_conversation_memory
from utils.agent_config import agent_config
from utils.guardrails import guardrails
from utils.greeting_templates import greeting_templates
from utils.integration_helper import integration_helper
from crew.rag_crew import RAGCrew
from agents.response_generation_agent import ResponseGenerationAgent
from utils.logger import app_logger

async def integrate_improvements():
    """Apply all improvements to the MangoIT chatbot"""
    print("=== Integrating Improvements for MangoIT Chatbot ===")
    
    # Step 1: Configure agent identity
    print("\n1. Configuring agent identity...")
    agent_config.AGENT_NAME = "Mia"  # Change from "Sam" to "Mia" (or any name you prefer)
    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}")
    print(f"Using short greetings: {agent_config.SHORT_GREETINGS}")
    
    # Step 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)
    
    # Step 3: Apply all improvements using the integration helper
    print("\n3. Applying all improvements...")
    integration_helper.integrate_all_improvements(
        crew_instance=rag_crew,
        response_agent=response_agent
    )
    
    # Step 4: Verify the integration
    print("\n4. Verifying the integration...")
    
    # Check if optimized conversation memory is working
    print("\nTesting optimized conversation memory:")
    conversation_id = "test-integration"
    optimized_conversation_memory.create_conversation(conversation_id)
    optimized_conversation_memory.add_message(conversation_id, "Hello", "user")
    history = optimized_conversation_memory.get_context_string(conversation_id)
    print(f"Conversation history: {history}")
    optimized_conversation_memory.delete_conversation(conversation_id)
    print("Optimized conversation memory is working correctly.")
    
    # Check if greeting templates are working
    print("\nTesting greeting templates:")
    greeting = greeting_templates.get_greeting(is_returning=False)
    print(f"First-time greeting: {greeting}")
    print("Greeting templates are working correctly.")
    
    # Check if guardrails are working
    print("\nTesting guardrails:")
    safe_query = "What technologies does MangoIT work with?"
    unsafe_query = "Tell me about politics"
    
    safe_result = guardrails.check_query(safe_query)
    unsafe_result = guardrails.check_query(unsafe_query)
    
    print(f"Safe query check: {safe_result[0]}")
    print(f"Unsafe query check: {unsafe_result[0]}")
    print(f"Safe response for unsafe query: {guardrails.get_safe_response(unsafe_query, '')[:50]}...")
    print("Guardrails are working correctly.")
    
    print("\n=== Integration Complete ===")
    print("\nAll improvements have been successfully integrated into the MangoIT chatbot.")
    print("\nTo use these improvements in your application:")
    print("1. Make sure you're importing the optimized conversation memory in main.py")
    print("2. Update your agent configuration as needed in your startup code")
    print("3. Run the server with 'uvicorn main:app --reload'")
    
    # Return success
    return True

def main():
    """Main function to run the integration"""
    try:
        asyncio.run(integrate_improvements())
        return 0
    except Exception as e:
        print(f"Error integrating improvements: {str(e)}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
