#!/bin/bash

# Test script for Phase 1 Element Checking functionality
# This script tests the new element checking commands in cremote

set -e

echo "=== Phase 1 Element Checking Test ==="
echo "Starting cremote daemon..."

# Start the daemon in the background
./cremotedaemon --debug &
DAEMON_PID=$!

# Wait for daemon to start
sleep 3

echo "Daemon started with PID: $DAEMON_PID"

# Function to cleanup on exit
cleanup() {
    echo "Cleaning up..."
    if [ ! -z "$DAEMON_PID" ]; then
        kill $DAEMON_PID 2>/dev/null || true
        wait $DAEMON_PID 2>/dev/null || true
    fi
    echo "Cleanup complete"
}

trap cleanup EXIT

# Test the new functionality using cremote client
echo ""
echo "=== Testing Element Checking Commands ==="

# Open a tab and load our test page
echo "Opening tab and loading test page..."
TAB_ID=$(./cremote open-tab)
echo "Tab ID: $TAB_ID"

# Get the absolute path to the test file
TEST_FILE="file://$(pwd)/test-element-checking.html"
echo "Loading: $TEST_FILE"
./cremote load-url --tab "$TAB_ID" --url "$TEST_FILE"

# Wait for page to load
sleep 2

echo ""
echo "=== Test 1: Check if elements exist ==="

# Test element existence
echo "Checking if main title exists..."
./cremote eval-js --tab "$TAB_ID" --code "
const result = {
    exists: document.querySelector('#main-title') !== null,
    count: document.querySelectorAll('#main-title').length
};
console.log('Element check result:', JSON.stringify(result));
result;
"

echo ""
echo "=== Test 2: Check visibility states ==="

# Test visible element
echo "Checking visible paragraph..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#visible-paragraph');
const result = {
    exists: element !== null,
    visible: element ? window.getComputedStyle(element).display !== 'none' : false,
    visibilityStyle: element ? window.getComputedStyle(element).visibility : null
};
console.log('Visible paragraph check:', JSON.stringify(result));
result;
"

# Test hidden element
echo "Checking hidden paragraph..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#hidden-paragraph');
const result = {
    exists: element !== null,
    visible: element ? window.getComputedStyle(element).display !== 'none' : false,
    displayStyle: element ? window.getComputedStyle(element).display : null
};
console.log('Hidden paragraph check:', JSON.stringify(result));
result;
"

echo ""
echo "=== Test 3: Check form element states ==="

# Test enabled vs disabled inputs
echo "Checking enabled input..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#text-input');
const result = {
    exists: element !== null,
    enabled: element ? !element.disabled : false,
    value: element ? element.value : null
};
console.log('Enabled input check:', JSON.stringify(result));
result;
"

echo "Checking disabled input..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#disabled-input');
const result = {
    exists: element !== null,
    enabled: element ? !element.disabled : false,
    disabled: element ? element.disabled : null
};
console.log('Disabled input check:', JSON.stringify(result));
result;
"

echo ""
echo "=== Test 4: Check selected/checked states ==="

# Test checked checkbox
echo "Checking checked checkbox..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#checkbox1');
const result = {
    exists: element !== null,
    checked: element ? element.checked : false,
    type: element ? element.type : null
};
console.log('Checked checkbox:', JSON.stringify(result));
result;
"

# Test unchecked checkbox
echo "Checking unchecked checkbox..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#checkbox2');
const result = {
    exists: element !== null,
    checked: element ? element.checked : false
};
console.log('Unchecked checkbox:', JSON.stringify(result));
result;
"

echo ""
echo "=== Test 5: Count multiple elements ==="

# Count elements with class 'item'
echo "Counting elements with class 'item'..."
./cremote eval-js --tab "$TAB_ID" --code "
const elements = document.querySelectorAll('.item');
const result = {
    count: elements.length,
    elements: Array.from(elements).map(el => ({
        tagName: el.tagName,
        textContent: el.textContent.trim(),
        dataId: el.getAttribute('data-id')
    }))
};
console.log('Item count result:', JSON.stringify(result));
result;
"

echo ""
echo "=== Test 6: Get element attributes ==="

# Get attributes of custom element
echo "Getting attributes of custom element..."
./cremote eval-js --tab "$TAB_ID" --code "
const element = document.querySelector('#custom-element');
const result = {
    exists: element !== null,
    attributes: {}
};
if (element) {
    // Get all attributes
    for (let attr of element.attributes) {
        result.attributes[attr.name] = attr.value;
    }
    // Get some computed styles
    const styles = window.getComputedStyle(element);
    result.computedStyles = {
        display: styles.display,
        color: styles.color,
        fontSize: styles.fontSize
    };
}
console.log('Custom element attributes:', JSON.stringify(result));
result;
"

echo ""
echo "=== Test 7: Focus testing ==="

# Test focus state
echo "Testing focus state..."
./cremote eval-js --tab "$TAB_ID" --code "
// Focus the test button
const button = document.querySelector('#test-button');
button.focus();

// Check if it's focused
const result = {
    buttonExists: button !== null,
    activeElement: document.activeElement ? document.activeElement.id : null,
    isFocused: document.activeElement === button
};
console.log('Focus test result:', JSON.stringify(result));
result;
"

echo ""
echo "=== All tests completed successfully! ==="
echo "The element checking functionality appears to be working correctly."
echo "Ready for Phase 1 MCP tool testing."

# Take a screenshot for verification
echo "Taking screenshot for verification..."
./cremote screenshot --tab "$TAB_ID" --output "test-phase1-screenshot.png"
echo "Screenshot saved as test-phase1-screenshot.png"

echo ""
echo "Test completed successfully!"
