#!/bin/bash

# Simple test for new daemon commands
set -e

echo "=== Testing New Daemon Commands ==="

# 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
        wait $DAEMON_PID 2>/dev/null || true
    fi
}
trap cleanup EXIT

# Test using curl to send commands directly to daemon
echo "Testing daemon commands via HTTP..."

# Open tab
echo "Opening tab..."
TAB_RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d '{"action": "open-tab", "params": {"timeout": "10"}}')
echo "Tab response: $TAB_RESPONSE"

# Extract tab ID (simple parsing)
TAB_ID=$(echo "$TAB_RESPONSE" | grep -o '"data":"[^"]*"' | cut -d'"' -f4)
echo "Tab ID: $TAB_ID"

if [ -z "$TAB_ID" ]; then
    echo "Failed to get tab ID"
    exit 1
fi

# Load a simple page
echo "Loading Google..."
curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d "{\"action\": \"load-url\", \"params\": {\"tab\": \"$TAB_ID\", \"url\": \"https://www.google.com\", \"timeout\": \"10\"}}"

sleep 3

# Test check-element command
echo "Testing check-element command..."
CHECK_RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d "{\"action\": \"check-element\", \"params\": {\"tab\": \"$TAB_ID\", \"selector\": \"input[name=q]\", \"type\": \"exists\", \"timeout\": \"5\"}}")
echo "Check element response: $CHECK_RESPONSE"

# Test count-elements command
echo "Testing count-elements command..."
COUNT_RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d "{\"action\": \"count-elements\", \"params\": {\"tab\": \"$TAB_ID\", \"selector\": \"input\", \"timeout\": \"5\"}}")
echo "Count elements response: $COUNT_RESPONSE"

# Test get-element-attributes command
echo "Testing get-element-attributes command..."
ATTR_RESPONSE=$(curl -s -X POST http://localhost:8989/command \
  -H "Content-Type: application/json" \
  -d "{\"action\": \"get-element-attributes\", \"params\": {\"tab\": \"$TAB_ID\", \"selector\": \"input[name=q]\", \"attributes\": \"name,type,placeholder\", \"timeout\": \"5\"}}")
echo "Get attributes response: $ATTR_RESPONSE"

echo "All daemon command tests completed!"
