#!/usr/bin/env python3
"""
LiveKit Room Connection Test

Tests the full bot with LiveKit room connection locally.
This script automates the entire flow:
1. Load environment variables from .env.local
2. Generate LiveKit access token
3. Run the bot with LiveKit room connection
4. Stream slideshow to the room
5. Log all activity for debugging

Usage:
    .venv/bin/python test_livekit_connection.py [room_name] [duration_seconds]
"""

import asyncio
import os
import sys
from pathlib import Path
from datetime import datetime
import time

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent))

# Load environment variables from .env.local
try:
    from dotenv import load_dotenv
    env_file = Path(__file__).parent / '.env.local'
    if env_file.exists():
        load_dotenv(env_file)
        print(f"[LiveKitTest] ✅ Loaded environment variables from {env_file}")
    else:
        print(f"[LiveKitTest] ❌ .env.local not found!")
        print(f"[LiveKitTest] Please create .env.local from .env.local.example")
        print(f"[LiveKitTest] You need:")
        print(f"[LiveKitTest]   - LIVEKIT_URL")
        print(f"[LiveKitTest]   - LIVEKIT_API_KEY")
        print(f"[LiveKitTest]   - LIVEKIT_API_SECRET")
        sys.exit(1)
except ImportError:
    print("[LiveKitTest] ❌ python-dotenv not installed")
    print("[LiveKitTest] Install with: .venv/bin/pip install python-dotenv")
    sys.exit(1)

# Import LiveKit API for token generation
try:
    from livekit.api import AccessToken, VideoGrants
except ImportError:
    print("[LiveKitTest] ❌ LiveKit API not installed")
    print("[LiveKitTest] Install with: .venv/bin/pip install livekit-api")
    sys.exit(1)

# Import the bot
from bot import ScreenshareBot
from test_local_capture import TeeLogger


def generate_token(room_name: str, identity: str) -> str:
    """Generate LiveKit access token"""
    api_key = os.getenv('LIVEKIT_API_KEY')
    api_secret = os.getenv('LIVEKIT_API_SECRET')

    if not api_key or not api_secret:
        raise ValueError(
            "Missing LIVEKIT_API_KEY or LIVEKIT_API_SECRET. "
            "Please set these in .env.local"
        )

    token = AccessToken(api_key, api_secret)
    token.with_identity(identity)
    token.with_name(f"Screenshare Bot ({identity})")
    token.with_grants(VideoGrants(
        room_join=True,
        room=room_name,
        can_publish=True,
        can_subscribe=True,
        can_publish_data=True
    ))

    return token.to_jwt()


async def test_livekit_connection(room_name: str, duration_seconds: int = 30):
    """Test bot with LiveKit room connection"""

    # Configuration
    livekit_url = os.getenv('LIVEKIT_URL')
    if not livekit_url:
        print("[LiveKitTest] ❌ LIVEKIT_URL not set in .env.local")
        sys.exit(1)

    deck_url = "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"
    session_id = f"test-session-{int(time.time())}"
    bot_id = f"test-bot-{int(time.time())}"
    identity = f"bot-{bot_id[:8]}"

    # Set up logging directory
    log_dir = Path("./test_logs")
    log_dir.mkdir(exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file = log_dir / f"livekit-test-{timestamp}.log"

    # Redirect stdout and stderr to both console and file
    stdout_logger = TeeLogger(log_file, "STDOUT")
    stderr_logger = TeeLogger(log_file, "STDERR")
    original_stdout = sys.stdout
    original_stderr = sys.stderr
    sys.stdout = stdout_logger
    sys.stderr = stderr_logger

    print("=" * 70)
    print("[LiveKitTest] LIVEKIT ROOM CONNECTION TEST")
    print("=" * 70)
    print(f"[LiveKitTest] Log file: {log_file}")
    print(f"[LiveKitTest] LiveKit URL: {livekit_url}")
    print(f"[LiveKitTest] Room name: {room_name}")
    print(f"[LiveKitTest] Deck URL: {deck_url}")
    print(f"[LiveKitTest] Session ID: {session_id}")
    print(f"[LiveKitTest] Bot ID: {bot_id}")
    print(f"[LiveKitTest] Test duration: {duration_seconds}s")
    print("=" * 70)
    print()

    # Generate access token
    print("[LiveKitTest] 🔑 Generating LiveKit access token...")
    try:
        token = generate_token(room_name, identity)
        print(f"[LiveKitTest] ✅ Token generated for identity: {identity}")
        print(f"[LiveKitTest] Token (first 20 chars): {token[:20]}...")
    except Exception as e:
        print(f"[LiveKitTest] ❌ Failed to generate token: {e}")
        sys.exit(1)

    # Construct room URL
    room_url = f"{livekit_url}/{room_name}"
    print(f"[LiveKitTest] 🌐 Room URL: {room_url}")
    print()

    # Create and start bot
    print("[LiveKitTest] 🤖 Creating bot instance...")
    bot = ScreenshareBot(
        room_url=room_url,
        deck_url=deck_url,
        session_id=session_id,
        bot_id=bot_id,
        meeting_token=token
    )

    try:
        print("[LiveKitTest] 🚀 Starting bot...")
        start_time = time.time()

        # Start the bot in a task
        bot_task = asyncio.create_task(bot.start())

        # Wait for the specified duration
        print(f"[LiveKitTest] ⏱️  Running for {duration_seconds} seconds...")
        print(f"[LiveKitTest] Press Ctrl+C to stop early")
        print()

        await asyncio.sleep(duration_seconds)

        # Stop the bot
        print()
        print("[LiveKitTest] ⏹️  Stopping bot...")
        await bot.stop()

        # Cancel the bot task
        bot_task.cancel()
        try:
            await bot_task
        except asyncio.CancelledError:
            pass

        elapsed = time.time() - start_time
        print()
        print("=" * 70)
        print("[LiveKitTest] TEST COMPLETE")
        print("=" * 70)
        print(f"[LiveKitTest] ✅ Bot ran for {elapsed:.1f} seconds")
        print(f"[LiveKitTest] ✅ Frames streamed: {bot.frame_count}")
        if elapsed > 0:
            print(f"[LiveKitTest] ✅ Average FPS: {bot.frame_count / elapsed:.2f}")

        # Get metrics
        if bot.screenshot_capture:
            capture_metrics = bot.screenshot_capture.metrics
            print(f"[LiveKitTest] 📊 Screenshot capture: {capture_metrics}")

        if bot.frame_processor:
            processor_stats = bot.frame_processor.get_performance_stats()
            print(f"[LiveKitTest] 📊 Frame processing: {processor_stats}")

        print("=" * 70)
        print(f"[LiveKitTest] 📁 Full log saved to: {log_file}")

    except KeyboardInterrupt:
        print()
        print("[LiveKitTest] ⚠️  Interrupted by user")
        await bot.stop()
    except Exception as e:
        print(f"[LiveKitTest] ❌ Error: {e}")
        import traceback
        traceback.print_exc()
        await bot.stop()
        sys.exit(1)
    finally:
        # Restore original stdout/stderr
        sys.stdout = original_stdout
        sys.stderr = original_stderr
        stdout_logger.close()
        stderr_logger.close()

        print(f"\n[LiveKitTest] ✅ Test complete. Log file: {log_file}")


def main():
    """Main entry point"""
    # Parse arguments
    room_name = sys.argv[1] if len(sys.argv) > 1 else "test-room-local"
    duration_seconds = int(sys.argv[2]) if len(sys.argv) > 2 else 30

    print(f"[LiveKitTest] Starting LiveKit connection test...")
    print(f"[LiveKitTest] Room: {room_name}, Duration: {duration_seconds}s")
    print()

    # Run the test
    try:
        asyncio.run(test_livekit_connection(room_name, duration_seconds))
    except KeyboardInterrupt:
        print("\n[LiveKitTest] Test interrupted by user")
    except Exception as e:
        print(f"\n[LiveKitTest] Fatal error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
