#!/usr/bin/env python3
"""
Test the full flow: create token with agent dispatch, then simulate participant joining
"""

import asyncio
import os
import json
from dotenv import load_dotenv
from livekit import api
from livekit.protocol.room import CreateRoomRequest, ListRoomsRequest, ListParticipantsRequest
from livekit.protocol.models import RoomConfiguration, RoomAgentDispatch

# Load environment variables
load_dotenv('/var/www/html/livekit_frontend/BackEnd/agent-starter-python/.env.local')

LIVEKIT_URL = os.getenv('LIVEKIT_URL')
API_KEY = os.getenv('LIVEKIT_API_KEY')
API_SECRET = os.getenv('LIVEKIT_API_SECRET')

async def test_full_flow():
    print("🔍 Testing Full Agent Dispatch Flow\n")
    
    # Create API client
    lk_api = api.LiveKitAPI(
        LIVEKIT_URL,
        API_KEY,
        API_SECRET,
    )
    
    try:
        room_name = f"test_flow_{int(asyncio.get_event_loop().time())}"
        agent_name = "default"
        
        print(f"Step 1: Creating room '{room_name}' with agent dispatch in config...")
        
        # Create room with agent dispatch configuration
        room_config = RoomConfiguration(
            agents=[
                RoomAgentDispatch(
                    agent_name=agent_name,
                    metadata='{"test": "flow"}'
                )
            ],
            metadata='{"agent_instructions": "Test instructions"}'
        )
        
        room = await lk_api.room.create_room(
            CreateRoomRequest(
                name=room_name,
                config=room_config
            )
        )
        
        print(f"✓ Room created: {room.name}")
        print(f"  - SID: {room.sid}")
        print(f"  - Participants: {room.num_participants}")
        print()
        
        print("Step 2: Waiting for agent to join (15 seconds)...")
        for i in range(15):
            await asyncio.sleep(1)
            print(f"  Waiting... {i+1}s", end='\r')
        print()
        
        print("\nStep 3: Checking room participants...")
        participants = await lk_api.room.list_participants(
            ListParticipantsRequest(room=room_name)
        )
        
        print(f"Participants in room: {len(participants.participants)}")
        for p in participants.participants:
            print(f"  - {p.identity} (kind: {p.kind})")
        
        if len(participants.participants) == 0:
            print("\n✗ ISSUE FOUND: Agent did not join the room!")
            print("\nPossible causes:")
            print("1. LiveKit Cloud free tier quota exhausted (1,000 agent minutes/month)")
            print("2. Agent dispatch not enabled for this LiveKit Cloud project")
            print("3. Worker not properly registered (but logs show it is registered)")
            print("4. Network/firewall issue preventing job dispatch")
            print("\n💡 Solution: Check LiveKit Cloud dashboard:")
            print("   - Go to https://cloud.livekit.io/")
            print("   - Check your project quota usage")
            print("   - Verify agent dispatch is enabled")
        else:
            print("\n✓ Agent successfully joined!")
        
        # Clean up
        print(f"\nStep 4: Cleaning up test room...")
        await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
        print("✓ Room deleted")
        
    except Exception as e:
        print(f"✗ Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        await lk_api.aclose()

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