#!/usr/bin/env python3
"""
Setup LiveKit SIP Inbound Trunk for Twilio
This script creates an inbound SIP trunk to accept calls from Twilio
"""
import asyncio
import os
from dotenv import load_dotenv
from livekit import api

# Load environment variables
load_dotenv(".env.local")

async def create_inbound_trunk():
    """Create an inbound SIP trunk for Twilio calls"""
    
    livekit_url = os.getenv("LIVEKIT_URL")
    livekit_key = os.getenv("LIVEKIT_API_KEY")
    livekit_secret = os.getenv("LIVEKIT_API_SECRET")
    twilio_phone = os.getenv("TWILIO_PHONE_NUMBER")
    
    if not all([livekit_url, livekit_key, livekit_secret, twilio_phone]):
        print("❌ Missing required environment variables:")
        print("   - LIVEKIT_URL")
        print("   - LIVEKIT_API_KEY")
        print("   - LIVEKIT_API_SECRET")
        print("   - TWILIO_PHONE_NUMBER")
        return
    
    print(f"🔧 Creating inbound SIP trunk for {twilio_phone}...")
    
    livekit_api = api.LiveKitAPI(
        url=livekit_url,
        api_key=livekit_key,
        api_secret=livekit_secret
    )
    
    try:
        # Create inbound trunk
        trunk = api.SIPInboundTrunkInfo(
            name="Twilio Inbound",
            numbers=[twilio_phone],
            krisp_enabled=True,  # Enable noise cancellation for better call quality
        )
        
        request = api.CreateSIPInboundTrunkRequest(trunk=trunk)
        result = await livekit_api.sip.create_sip_inbound_trunk(request)
        
        print(f"✅ Inbound trunk created successfully!")
        print(f"   Trunk ID: {result.sip_trunk_id}")
        print(f"   Name: {result.name}")
        print(f"   Numbers: {result.numbers}")
        print(f"\n📋 Next step: Create a dispatch rule to route calls to your agent")
        
    except Exception as e:
        if "already exists" in str(e).lower():
            print(f"ℹ️  Trunk already exists for {twilio_phone}")
            print(f"   You can view it in the LiveKit dashboard")
        else:
            print(f"❌ Error creating trunk: {e}")
    
    finally:
        await livekit_api.aclose()

async def list_existing_trunks():
    """List all existing inbound trunks"""
    
    livekit_url = os.getenv("LIVEKIT_URL")
    livekit_key = os.getenv("LIVEKIT_API_KEY")
    livekit_secret = os.getenv("LIVEKIT_API_SECRET")
    
    livekit_api = api.LiveKitAPI(
        url=livekit_url,
        api_key=livekit_key,
        api_secret=livekit_secret
    )
    
    try:
        print("\n📋 Listing existing inbound trunks...")
        trunks = await livekit_api.sip.list_sip_inbound_trunk(
            api.ListSIPInboundTrunkRequest()
        )
        
        if not trunks.items:
            print("   No inbound trunks found")
        else:
            for trunk in trunks.items:
                print(f"\n   Trunk: {trunk.name}")
                print(f"   ID: {trunk.sip_trunk_id}")
                print(f"   Numbers: {trunk.numbers}")
                print(f"   Krisp enabled: {trunk.krisp_enabled}")
        
    except Exception as e:
        print(f"❌ Error listing trunks: {e}")
    
    finally:
        await livekit_api.aclose()

async def main():
    print("=" * 60)
    print("LiveKit SIP Trunk Setup for Twilio")
    print("=" * 60)
    
    # List existing trunks first
    await list_existing_trunks()
    
    # Create new trunk
    await create_inbound_trunk()
    
    print("\n" + "=" * 60)

if __name__ == "__main__":
    asyncio.run(main())
