#!/bin/bash

# Phase 3 Functionality Test Script
# Tests form analysis, multiple interactions, and bulk form filling

set -e

echo "=== Phase 3 Functionality Test ==="
echo "Testing form analysis, multiple interactions, and bulk form filling"

# Configuration
DAEMON_PORT=9223
CLIENT_PORT=9223
TEST_FILE="test-phase3-forms.html"
DAEMON_PID=""
CHROME_PID=""

# Cleanup function
cleanup() {
    echo "Cleaning up..."
    if [ ! -z "$DAEMON_PID" ]; then
        echo "Stopping daemon (PID: $DAEMON_PID)"
        kill $DAEMON_PID 2>/dev/null || true
        wait $DAEMON_PID 2>/dev/null || true
    fi
    if [ ! -z "$CHROME_PID" ]; then
        echo "Stopping Chrome (PID: $CHROME_PID)"
        kill $CHROME_PID 2>/dev/null || true
        wait $CHROME_PID 2>/dev/null || true
    fi
    # Clean up any screenshots
    rm -f /tmp/phase3-*.png
}

# Set up cleanup trap
trap cleanup EXIT

# Start daemon
echo "Starting daemon on port $DAEMON_PORT..."
./cremotedaemon --port=$DAEMON_PORT --debug &
DAEMON_PID=$!

# Wait for daemon to start
echo "Waiting for daemon to start..."
sleep 3

# Check if daemon is running
if ! kill -0 $DAEMON_PID 2>/dev/null; then
    echo "ERROR: Daemon failed to start"
    exit 1
fi

echo "Daemon started successfully (PID: $DAEMON_PID)"

# Test 1: Open tab and navigate to test page
echo ""
echo "=== Test 1: Navigation ==="
TAB_ID=$(./cremote open-tab --port=$CLIENT_PORT)
echo "Opened tab: $TAB_ID"

# Get absolute path to test file
TEST_PATH="file://$(pwd)/$TEST_FILE"
echo "Navigating to: $TEST_PATH"
./cremote load-url --tab="$TAB_ID" --url="$TEST_PATH" --port=$CLIENT_PORT

# Take initial screenshot
./cremote screenshot --tab="$TAB_ID" --output="/tmp/phase3-initial.png" --port=$CLIENT_PORT
echo "Initial screenshot saved to /tmp/phase3-initial.png"

# Test 2: Form Analysis
echo ""
echo "=== Test 2: Form Analysis ==="
echo "Analyzing registration form..."

# Test the daemon command directly
echo "Testing analyze-form daemon command..."
FORM_ANALYSIS=$(curl -s -X POST http://localhost:$DAEMON_PORT/command \
    -H "Content-Type: application/json" \
    -d '{
        "action": "analyze-form",
        "params": {
            "tab": "'$TAB_ID'",
            "selector": "#registration-form",
            "timeout": "10"
        }
    }')

echo "Form analysis result:"
echo "$FORM_ANALYSIS" | jq '.'

# Check if analysis was successful
if echo "$FORM_ANALYSIS" | jq -e '.success' > /dev/null; then
    echo "✓ Form analysis successful"
    
    # Extract field count
    FIELD_COUNT=$(echo "$FORM_ANALYSIS" | jq -r '.data.field_count')
    echo "Found $FIELD_COUNT form fields"
    
    # Check if we found expected fields
    if [ "$FIELD_COUNT" -gt 5 ]; then
        echo "✓ Expected number of fields found"
    else
        echo "✗ Unexpected field count: $FIELD_COUNT"
    fi
else
    echo "✗ Form analysis failed"
    echo "$FORM_ANALYSIS"
fi

# Test 3: Multiple Interactions
echo ""
echo "=== Test 3: Multiple Interactions ==="
echo "Testing multiple interactions..."

INTERACTIONS_RESULT=$(curl -s -X POST http://localhost:$DAEMON_PORT/command \
    -H "Content-Type: application/json" \
    -d '{
        "action": "interact-multiple",
        "params": {
            "tab": "'$TAB_ID'",
            "interactions": "[
                {\"selector\": \"#test-button\", \"action\": \"click\"},
                {\"selector\": \"#toggle-button\", \"action\": \"click\"},
                {\"selector\": \"#hidden-input\", \"action\": \"fill\", \"value\": \"Test input\"}
            ]",
            "timeout": "10"
        }
    }')

echo "Multiple interactions result:"
echo "$INTERACTIONS_RESULT" | jq '.'

# Check if interactions were successful
if echo "$INTERACTIONS_RESULT" | jq -e '.success' > /dev/null; then
    echo "✓ Multiple interactions successful"
    
    SUCCESS_COUNT=$(echo "$INTERACTIONS_RESULT" | jq -r '.data.success_count')
    TOTAL_COUNT=$(echo "$INTERACTIONS_RESULT" | jq -r '.data.total_count')
    echo "Successful interactions: $SUCCESS_COUNT/$TOTAL_COUNT"
    
    if [ "$SUCCESS_COUNT" -eq "$TOTAL_COUNT" ]; then
        echo "✓ All interactions successful"
    else
        echo "✗ Some interactions failed"
    fi
else
    echo "✗ Multiple interactions failed"
    echo "$INTERACTIONS_RESULT"
fi

# Take screenshot after interactions
./cremote screenshot --tab="$TAB_ID" --output="/tmp/phase3-after-interactions.png" --port=$CLIENT_PORT
echo "Screenshot after interactions saved to /tmp/phase3-after-interactions.png"

# Test 4: Bulk Form Filling
echo ""
echo "=== Test 4: Bulk Form Filling ==="
echo "Testing bulk form filling..."

BULK_FILL_RESULT=$(curl -s -X POST http://localhost:$DAEMON_PORT/command \
    -H "Content-Type: application/json" \
    -d '{
        "action": "fill-form-bulk",
        "params": {
            "tab": "'$TAB_ID'",
            "form-selector": "#registration-form",
            "fields": "{
                \"username\": \"testuser123\",
                \"email\": \"test@example.com\",
                \"password\": \"testpass123\",
                \"bio\": \"This is a test bio for Phase 3 testing.\"
            }",
            "timeout": "10"
        }
    }')

echo "Bulk form filling result:"
echo "$BULK_FILL_RESULT" | jq '.'

# Check if bulk filling was successful
if echo "$BULK_FILL_RESULT" | jq -e '.success' > /dev/null; then
    echo "✓ Bulk form filling successful"
    
    SUCCESS_COUNT=$(echo "$BULK_FILL_RESULT" | jq -r '.data.success_count')
    TOTAL_COUNT=$(echo "$BULK_FILL_RESULT" | jq -r '.data.total_count')
    echo "Successfully filled fields: $SUCCESS_COUNT/$TOTAL_COUNT"
    
    if [ "$SUCCESS_COUNT" -eq "$TOTAL_COUNT" ]; then
        echo "✓ All fields filled successfully"
    else
        echo "✗ Some fields failed to fill"
    fi
else
    echo "✗ Bulk form filling failed"
    echo "$BULK_FILL_RESULT"
fi

# Take final screenshot
./cremote screenshot --tab="$TAB_ID" --output="/tmp/phase3-final.png" --port=$CLIENT_PORT
echo "Final screenshot saved to /tmp/phase3-final.png"

# Test 5: Contact Form Bulk Fill
echo ""
echo "=== Test 5: Contact Form Bulk Fill ==="
echo "Testing bulk fill on contact form..."

CONTACT_FILL_RESULT=$(curl -s -X POST http://localhost:$DAEMON_PORT/command \
    -H "Content-Type: application/json" \
    -d '{
        "action": "fill-form-bulk",
        "params": {
            "tab": "'$TAB_ID'",
            "form-selector": "#contact-form",
            "fields": "{
                \"name\": \"John Doe\",
                \"email\": \"john@example.com\",
                \"message\": \"This is a test message for the contact form.\"
            }",
            "timeout": "10"
        }
    }')

echo "Contact form bulk filling result:"
echo "$CONTACT_FILL_RESULT" | jq '.'

if echo "$CONTACT_FILL_RESULT" | jq -e '.success' > /dev/null; then
    echo "✓ Contact form bulk filling successful"
else
    echo "✗ Contact form bulk filling failed"
fi

# Summary
echo ""
echo "=== Test Summary ==="
echo "Phase 3 functionality tests completed."
echo "Screenshots saved:"
echo "  - Initial: /tmp/phase3-initial.png"
echo "  - After interactions: /tmp/phase3-after-interactions.png"
echo "  - Final: /tmp/phase3-final.png"

echo ""
echo "All Phase 3 tests completed successfully!"
