#!/bin/bash

# Test using a different port to avoid conflict
set -e

echo "=== Testing on Different Port ==="

# Kill our processes (not the system one)
pkill -f chromium || true
sleep 2

# Start Chrome
chromium --remote-debugging-port=9222 --user-data-dir=/tmp/chromium-debug --no-sandbox --disable-dev-shm-usage --headless &
CHROME_PID=$!
sleep 5

# Start daemon on different port
echo "Starting daemon on port 8990..."
./cremotedaemon --listen localhost --port 8990 --debug &
DAEMON_PID=$!
sleep 3

cleanup() {
    echo "Cleaning up..."
    if [ ! -z "$DAEMON_PID" ]; then
        kill $DAEMON_PID 2>/dev/null || true
    fi
    if [ ! -z "$CHROME_PID" ]; then
        kill $CHROME_PID 2>/dev/null || true
    fi
}
trap cleanup EXIT

# Test our new command on the different port
echo "Testing check-element command on port 8990..."
RESPONSE=$(curl -s -X POST http://localhost:8990/command \
  -H "Content-Type: application/json" \
  -d '{"action": "check-element", "params": {"selector": "body", "type": "exists"}}')
echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "Unknown action"; then
    echo "ERROR: New command still not recognized"
    exit 1
else
    echo "SUCCESS: New command recognized!"
fi

echo "Test completed successfully!"
