#!/usr/bin/env python3
"""
Local Integration Test for Tavus Tool Forwarder Bot

Tests the bot's ability to:
1. Initialize and connect to Daily.co
2. Join a room
3. Listen for app-messages
4. Process tool calls
5. Forward to backend API

Usage:
    python test_bot_local.py <daily_room_url>
"""

import asyncio
import sys
import os
from typing import Dict, Any, Optional
from dotenv import load_dotenv

# Load environment before importing bot
load_dotenv()

# Now import bot
from bot import TavusToolForwarderBot, logger

async def test_bot_connection(room_url: str) -> bool:
    """Test bot can connect and stay alive"""

    print("\n" + "=" * 70)
    print("LOCAL INTEGRATION TEST - TAVUS TOOL FORWARDER BOT")
    print("=" * 70)
    print(f"\nTest Room: {room_url}")
    print(f"Backend API: {os.getenv('API_BASE_URL', 'https://slide-system-production-5813.up.railway.app')}")
    print(f"Daily API Key: {os.getenv('DAILY_API_KEY', 'NOT SET')[:15]}...")
    print("\n" + "=" * 70)

    if not os.getenv('DAILY_API_KEY'):
        print("\n❌ ERROR: DAILY_API_KEY environment variable not set!")
        print("Set it in .env file or export it:")
        print("  export DAILY_API_KEY=your_key_here")
        return False

    try:
        print("\n📡 Creating bot instance...")
        bot = TavusToolForwarderBot(room_url, bot_id="test-bot-local", session_id="test-session")
        print("✓ Bot instance created")

        print("\n🚀 Starting bot (will run for 30 seconds)...")
        print("💡 Join the room in another browser tab to test")
        print("💡 Trigger a tool call from Tavus avatar to test forwarding")
        print()

        # Run bot with a timeout for testing
        await asyncio.wait_for(bot.run(), timeout=30.0)

        # If bot completes without timeout, it's still a success
        print("\n✓ Bot completed normally")
        return True

    except asyncio.TimeoutError:
        print("\n✓ Test completed (30 second timeout reached)")
        print("Check logs above to verify:")
        print("  1. Bot joined room successfully")
        print("  2. Bot received any app-messages")
        print("  3. Tool calls were forwarded to backend")
        return True

    except Exception as e:
        print(f"\n❌ TEST FAILED: {e}")
        logger.error(f"Test error: {e}", exc_info=True)
        return False


async def test_mock_tool_call() -> bool:
    """Test bot's tool call processing logic without Daily.co"""

    print("\n" + "=" * 70)
    print("UNIT TEST - TOOL CALL PROCESSING")
    print("=" * 70)

    # Mock tool call message
    mock_message: Dict[str, Any] = {
        'event_type': 'conversation.tool_call',
        'conversation_id': 'test123',
        'properties': {
            'name': 'generate_custom_deck',
            'arguments': '{"company_name":"TestCorp","pain_points":["slow demos"],"interested_features":["automation"]}'
        }
    }

    print("\n📨 Mock tool call message:")
    print(f"   {mock_message}")

    # Create bot instance (won't join room)
    fake_room: str = "https://test.daily.co/test-room"
    bot: TavusToolForwarderBot = TavusToolForwarderBot(fake_room, bot_id="test-mock-bot", session_id="test-mock-session")

    print("\n🧪 Testing tool call processing...")

    try:
        # Test the on_app_message handler directly (sync method)
        bot.on_app_message(mock_message, "mock_sender")

        # Give async tasks time to complete
        await asyncio.sleep(2)

        print("✓ Tool call processing completed")
        return True

    except Exception as e:
        print(f"❌ Tool call processing failed: {e}")
        logger.error(f"Mock test error: {e}", exc_info=True)
        return False


async def main() -> None:
    """Run all tests"""

    print("\n" + "#" * 70)
    print("# TAVUS TOOL FORWARDER BOT - LOCAL TEST SUITE")
    print("#" * 70)

    # Test 1: Mock tool call processing (no network)
    print("\n\n[TEST 1/2] Mock Tool Call Processing (Unit Test)")
    print("-" * 70)
    test1_passed: bool = await test_mock_tool_call()

    # Test 2: Live connection test (if room URL provided)
    print("\n\n[TEST 2/2] Live Bot Connection (Integration Test)")
    print("-" * 70)

    test2_passed: Optional[bool]
    if len(sys.argv) > 1:
        room_url: str = sys.argv[1]
        test2_passed = await test_bot_connection(room_url)
    else:
        print("⏭️  SKIPPED - No room URL provided")
        print("   Usage: python test_bot_local.py <daily_room_url>")
        test2_passed = None

    # Summary
    print("\n\n" + "=" * 70)
    print("TEST SUMMARY")
    print("=" * 70)
    print(f"Mock Tool Call Processing: {'✅ PASSED' if test1_passed else '❌ FAILED'}")
    if test2_passed is not None:
        print(f"Live Bot Connection:       {'✅ PASSED' if test2_passed else '❌ FAILED'}")
    else:
        print(f"Live Bot Connection:       ⏭️  SKIPPED")
    print("=" * 70)


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