#!/bin/bash

# Test existing commands to make sure basic setup works
set -e

echo "=== Testing Existing Commands ==="

# Kill any existing processes
pkill -f chromium || true
pkill -f cremotedaemon || true
sleep 2

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

# Verify Chrome is responding
echo "Checking Chrome DevTools..."
curl -s http://localhost:9222/json/version || {
    echo "Chrome DevTools not responding"
    exit 1
}

# Start daemon
echo "Starting daemon..."
./cremotedaemon --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 existing command
echo "Testing open-tab command..."
RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d '{"action": "open-tab", "params": {"timeout": "10"}}')
echo "Open tab response: $RESPONSE"

if echo "$RESPONSE" | grep -q "Unknown action"; then
    echo "ERROR: Even existing commands don't work!"
    exit 1
fi

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

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

echo "Test completed successfully!"
