"""
Simple example of using the frontend chat endpoint
"""

import requests
import time
import json
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# API URL
API_URL = os.getenv("API_URL", "http://localhost:8000")

# Generate a unique conversation ID if not provided
import uuid
conversation_id = str(uuid.uuid4())

def send_message(message, wait_for_response=True, timeout=30):
    """
    Send a message to the frontend chat endpoint
    
    Args:
        message: The message to send
        wait_for_response: Whether to wait for the response or return immediately
        timeout: Maximum time to wait for a response in seconds
    """
    global conversation_id
    
    print(f"\nYou: {message}")
    
    # Prepare the request payload
    payload = {
        "message": message,
        "conversation_id": conversation_id,
        "timeout": timeout,
        "wait_for_response": wait_for_response
    }
    
    # Send the request
    try:
        response = requests.post(f"{API_URL}/frontend/chat", json=payload)
        response.raise_for_status()  # Raise an exception for 4XX/5XX responses
        data = response.json()
        
        # Save conversation ID for future messages
        conversation_id = data["conversation_id"]
        print(f"Conversation ID: {conversation_id[:8]}...")
        
        if data["complete"]:
            # Response is complete
            print(f"\nAssistant: {data['reply']}")
            
            # Print sources if available
            if data["sources"] and len(data["sources"]) > 0:
                print("\nSources:")
                for source in data["sources"]:
                    print(f"- {source['source']} (relevance: {source['relevance']})")
        else:
            # Response is not complete
            print(f"\nAssistant: {data['reply']} (still processing... {data['progress']}%)")
            
            # Poll for updates if we have a task ID
            task_id = data["task_id"]
            if task_id and wait_for_response:
                poll_for_updates(task_id)
    
    except requests.exceptions.RequestException as e:
        print(f"\nError: {str(e)}")

def poll_for_updates(task_id, max_attempts=10):
    """
    Poll for updates on a task
    
    Args:
        task_id: The task ID to poll
        max_attempts: Maximum number of polling attempts
    """
    global conversation_id
    
    print(f"Polling for updates on task {task_id[:8]}...")
    attempts = 0
    
    while attempts < max_attempts:
        try:
            # Wait between polls
            time.sleep(2)
            attempts += 1
            
            # Create a polling request
            poll_payload = {
                "message": "",  # Empty message for polling
                "conversation_id": conversation_id,
                "wait_for_response": True,
                "timeout": 5  # Short timeout for polling
            }
            
            # Send the polling request
            poll_response = requests.post(f"{API_URL}/frontend/chat", json=poll_payload)
            poll_response.raise_for_status()
            poll_data = poll_response.json()
            
            if poll_data["complete"]:
                # Response is complete
                print(f"\nAssistant: {poll_data['reply']}")
                
                # Print sources if available
                if poll_data["sources"] and len(poll_data["sources"]) > 0:
                    print("\nSources:")
                    for source in poll_data["sources"]:
                        print(f"- {source['source']} (relevance: {source['relevance']})")
                
                return
            else:
                # Response is not complete
                print(f"Progress: {poll_data['progress']}%")
        
        except requests.exceptions.RequestException as e:
            print(f"\nError polling for updates: {str(e)}")
            return

def main():
    """Main function"""
    print("=== MangoIT AI Chatbot Frontend Example ===")
    print("Type 'exit', 'quit', or 'bye' to exit")
    
    while True:
        # Get user input
        user_input = input("\nYou: ")
        
        # Check if the user wants to exit
        if user_input.lower() in ["exit", "quit", "bye"]:
            print("Goodbye!")
            break
        
        # Send the message
        send_message(user_input)

if __name__ == "__main__":
    main()
