#!/usr/bin/env python3
"""
Check LiveKit Cloud configuration and agent dispatch settings
"""

import os
import sys
import requests
from dotenv import load_dotenv

# 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')

print("🔍 Checking LiveKit Configuration\n")
print(f"LiveKit URL: {LIVEKIT_URL}")
print(f"API Key: {API_KEY}")
print(f"API Secret: {'*' * 20}{API_SECRET[-10:] if API_SECRET else 'NOT SET'}")
print()

# Extract the host from the WebSocket URL
if LIVEKIT_URL:
    host = LIVEKIT_URL.replace('wss://', '').replace('ws://', '')
    api_url = f"https://{host}"
    print(f"API URL: {api_url}")
    print()
    
    # Try to list rooms
    print("Attempting to list rooms...")
    try:
        from livekit import api
        
        # Create API client
        lk_api = api.LiveKitAPI(
            LIVEKIT_URL,
            API_KEY,
            API_SECRET,
        )
        
        # List rooms
        rooms = lk_api.room.list_rooms()
        print(f"✓ Successfully connected to LiveKit API")
        print(f"  Active rooms: {len(rooms)}")
        for room in rooms:
            print(f"    - {room.name} ({room.num_participants} participants)")
        print()
        
    except Exception as e:
        print(f"✗ Failed to connect to LiveKit API: {e}")
        print()
        
    # Check if agent dispatch is configured
    print("Agent Dispatch Configuration:")
    print("  - Agent name: 'default'")
    print("  - Worker registered: Check backend logs for 'registered worker'")
    print()
    
    print("🔍 Troubleshooting Steps:")
    print("1. Verify the backend is running and registered (check backend.log)")
    print("2. Check LiveKit Cloud dashboard for agent dispatch configuration")
    print("3. Ensure the project has agent dispatch enabled")
    print("4. Verify the agent name matches ('default')")
    print()
    
else:
    print("✗ LIVEKIT_URL is not set!")
    sys.exit(1)
