#!/bin/bash

# Minimal test to check if daemon recognizes new commands
set -e

echo "=== Minimal Daemon Command Test ==="

# Start Chrome first
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

# 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 if daemon recognizes the new commands (should not return "Unknown action")
echo "Testing if daemon recognizes 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 "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "Unknown action"; then
    echo "ERROR: Daemon does not recognize check-element command!"
    exit 1
else
    echo "SUCCESS: Daemon recognizes check-element command"
fi

echo "Testing if daemon recognizes count-elements command..."
RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d '{"action": "count-elements", "params": {"selector": "body"}}')
echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "Unknown action"; then
    echo "ERROR: Daemon does not recognize count-elements command!"
    exit 1
else
    echo "SUCCESS: Daemon recognizes count-elements command"
fi

echo "Testing if daemon recognizes get-element-attributes command..."
RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d '{"action": "get-element-attributes", "params": {"selector": "body", "attributes": "all"}}')
echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "Unknown action"; then
    echo "ERROR: Daemon does not recognize get-element-attributes command!"
    exit 1
else
    echo "SUCCESS: Daemon recognizes get-element-attributes command"
fi

echo "All commands are recognized by the daemon!"
