#!/bin/bash

# LiveKit Transport Testing Script
# Tests the screenshare bot with LiveKit transport
#
# Usage:
#   ./scripts/test_livekit.sh [duration_seconds]
#
# Environment variables required:
#   LIVEKIT_URL       - LiveKit WebSocket URL (e.g., wss://project.livekit.cloud)
#   LIVEKIT_API_KEY   - LiveKit API key for token generation
#   LIVEKIT_API_SECRET - LiveKit API secret for token generation
#
# Optional:
#   TEST_DECK_URL     - Custom deck URL (defaults to test fixture or remote test deck)
#   TEST_DURATION     - Test duration in seconds (default: 30)

set -e

echo "=========================================="
echo "LiveKit Transport Testing"
echo "=========================================="
echo ""

# Check environment variables
if [ -z "$LIVEKIT_URL" ]; then
    echo "❌ LIVEKIT_URL not set"
    echo "   Example: export LIVEKIT_URL=wss://your-project.livekit.cloud"
    exit 1
fi

if [ -z "$LIVEKIT_API_KEY" ]; then
    echo "❌ LIVEKIT_API_KEY not set"
    echo "   Get your API key from LiveKit Cloud dashboard"
    exit 1
fi

if [ -z "$LIVEKIT_API_SECRET" ]; then
    echo "❌ LIVEKIT_API_SECRET not set"
    echo "   Get your API secret from LiveKit Cloud dashboard"
    exit 1
fi

echo "✅ Environment variables configured"
echo ""

# Determine test duration (from argument, env var, or default)
TEST_DURATION=${1:-${TEST_DURATION:-30}}
echo "Test duration: ${TEST_DURATION} seconds"
echo ""

# Determine deck URL
if [ -n "$TEST_DECK_URL" ]; then
    DECK_URL="$TEST_DECK_URL"
elif [ -f "tests/fixtures/test_deck.html" ]; then
    DECK_URL="file://$(pwd)/tests/fixtures/test_deck.html"
    echo "✅ Using local test deck fixture"
else
    DECK_URL="https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"
    echo "⚠️  Test deck fixture not found, using remote test deck"
fi

# Generate test session ID and bot ID
SESSION_ID=$(python3 -c "import uuid; print(str(uuid.uuid4()))")
BOT_ID=$(python3 -c "import uuid; print(str(uuid.uuid4()))")
ROOM_NAME="test-room-$(date +%s)"

echo ""
echo "Test Configuration:"
echo "  Transport: livekit"
echo "  Room: $ROOM_NAME"
echo "  Deck: $DECK_URL"
echo "  Session ID: $SESSION_ID"
echo "  Bot ID: $BOT_ID"
echo "  LiveKit URL: $LIVEKIT_URL"
echo ""

# Construct full room URL
ROOM_URL="$LIVEKIT_URL/$ROOM_NAME"

# Set transport type environment variable
export TRANSPORT_TYPE=livekit

# Check if bot.py exists
if [ ! -f "bot.py" ]; then
    echo "❌ bot.py not found. Please run this script from the screenshare-bot directory."
    exit 1
fi

# Run bot with timeout
echo "Starting bot (${TEST_DURATION} second test)..."
echo "Press Ctrl+C to stop early"
echo ""

# Run bot with timeout (allow it to fail gracefully)
timeout ${TEST_DURATION}s python3 bot.py \
    "$ROOM_URL" \
    "$DECK_URL" \
    "$SESSION_ID" \
    "$BOT_ID" \
    "" \
    1 2>&1 || EXIT_CODE=$?

# Check exit code
if [ -z "$EXIT_CODE" ]; then
    echo ""
    echo "⚠️  Bot exited before timeout"
    EXIT_CODE=0
elif [ $EXIT_CODE -eq 124 ]; then
    echo ""
    echo "✅ Test completed (timeout reached)"
    EXIT_CODE=0
else
    echo ""
    echo "❌ Bot exited with error code: $EXIT_CODE"
fi

echo ""
echo "=========================================="
echo "Test Summary"
echo "=========================================="
echo ""
echo "Room: $ROOM_NAME"
echo "Duration: ${TEST_DURATION} seconds"
echo ""
echo "Manual verification checklist:"
echo "  [ ] Check LiveKit Cloud dashboard"
echo "  [ ] Verify room '$ROOM_NAME' was created"
echo "  [ ] Verify screen share track was published"
echo "  [ ] Check for any errors in the logs above"
echo ""
echo "LiveKit Cloud Dashboard:"
echo "  https://cloud.livekit.io/"
echo ""

# If Railway is being used, show Railway logs hint
if [ -n "$RAILWAY_ENVIRONMENT" ]; then
    echo "Railway logs:"
    echo "  railway logs --tail 100"
    echo ""
fi

echo "To test with a real client:"
echo "  1. Open LiveKit example client: https://meet.livekit.io/"
echo "  2. Connect to room: $ROOM_NAME"
echo "  3. Verify you see the screen share stream"
echo ""

exit $EXIT_CODE
