"""
Test script for appointment scheduling feature
"""

import asyncio
import uuid
import httpx
import json
from pprint import pprint

# API URL
API_URL = "http://localhost:8000"

async def test_meeting_intent_detection():
    """Test the meeting intent detection endpoint"""
    print("\n=== Testing Meeting Intent Detection ===")
    
    # Test messages
    test_messages = [
        "I want to schedule a meeting to discuss a project",
        "Can I get a quote for your services?",
        "I'd like to talk to someone about pricing",
        "What are your office hours?",
        "Tell me about your web development services"
    ]
    
    async with httpx.AsyncClient() as client:
        for message in test_messages:
            print(f"\nTesting message: '{message}'")
            response = await client.get(
                f"{API_URL}/appointment/detect-intent",
                params={"message": message}
            )
            
            if response.status_code == 200:
                result = response.json()
                print(f"Is meeting request: {result['is_meeting_request']}")
                print(f"Confidence: {result['confidence']}")
                print(f"Suggested topic: {result['suggested_topic']}")
                print(f"Missing fields: {', '.join(result['missing_fields']) if result['missing_fields'] else 'None'}")
            else:
                print(f"Error: {response.status_code} - {response.text}")


async def test_appointment_scheduling():
    """Test the appointment scheduling endpoint"""
    print("\n=== Testing Appointment Scheduling ===")
    
    # Create a test appointment request
    appointment_request = {
        "name": "Test User",
        "email": "test@example.com",
        "phone": "123-456-7890",
        "company": "Test Company",
        "topic": "Website Development Project",
        "preferred_date": "2025-10-01",
        "preferred_time": "14:00",
        "additional_notes": "This is a test appointment",
        "conversation_id": str(uuid.uuid4())
    }
    
    print("Scheduling appointment with the following details:")
    pprint(appointment_request)
    
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{API_URL}/appointment/schedule",
            json=appointment_request
        )
        
        if response.status_code == 200:
            result = response.json()
            print("\nAppointment scheduled successfully:")
            pprint(result)
            
            # Test getting the appointment details
            appointment_id = result["appointment_id"]
            print(f"\nFetching details for appointment {appointment_id}:")
            
            get_response = await client.get(f"{API_URL}/appointment/{appointment_id}")
            
            if get_response.status_code == 200:
                appointment_details = get_response.json()
                print("Appointment details:")
                pprint(appointment_details)
            else:
                print(f"Error getting appointment: {get_response.status_code} - {get_response.text}")
                
            # Test listing all appointments
            print("\nListing all appointments:")
            list_response = await client.get(f"{API_URL}/appointment/list")
            
            if list_response.status_code == 200:
                appointments = list_response.json()
                print(f"Found {len(appointments)} appointments:")
                for i, appointment in enumerate(appointments):
                    print(f"\nAppointment {i+1}:")
                    pprint(appointment)
            else:
                print(f"Error listing appointments: {list_response.status_code} - {list_response.text}")
        else:
            print(f"Error scheduling appointment: {response.status_code} - {response.text}")


async def test_frontend_chat_with_meeting_intent():
    """Test the frontend chat endpoint with meeting intent"""
    print("\n=== Testing Frontend Chat with Meeting Intent ===")
    
    # Create a conversation ID
    conversation_id = str(uuid.uuid4())
    print(f"Using conversation ID: {conversation_id}")
    
    # Test messages that should trigger meeting intent
    test_messages = [
        "I'd like to schedule a consultation about a new website project",
        "My name is John Smith and my email is john@example.com",
        "You can reach me at 555-123-4567"
    ]
    
    async with httpx.AsyncClient() as client:
        for i, message in enumerate(test_messages):
            print(f"\nSending message {i+1}: '{message}'")
            
            response = await client.post(
                f"{API_URL}/frontend/chat",
                json={
                    "message": message,
                    "conversation_id": conversation_id,
                    "wait_for_response": True,
                    "timeout": 30
                }
            )
            
            if response.status_code == 200:
                result = response.json()
                print(f"Response: {result['reply']}")
                print(f"Complete: {result['complete']}")
                print(f"Progress: {result['progress']}")
            else:
                print(f"Error: {response.status_code} - {response.text}")
            
            # Wait a bit between messages
            await asyncio.sleep(1)


async def main():
    """Run all tests"""
    try:
        await test_meeting_intent_detection()
        await test_appointment_scheduling()
        await test_frontend_chat_with_meeting_intent()
    except Exception as e:
        print(f"Error running tests: {str(e)}")


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