#!/usr/bin/env bash

# Test Connectors
# This script tests the Besu-Firefly, Besu-Cacti, and Firefly-Cacti connectors

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Configuration
BESU_RPC_URL="${BESU_RPC_URL:-http://besu-rpc-service.besu-network.svc.cluster.local:8545}"
FIREFLY_API_URL="${FIREFLY_API_URL:-http://firefly-api.firefly.svc.cluster.local:5000}"
CACTUS_API_URL="${CACTUS_API_URL:-http://cactus-api.cacti.svc.cluster.local:4000}"


log_success "Testing Connectors..."

# Test Besu connection
log_warn "Testing Besu connection..."
if curl -s -X POST "$BESU_RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' | grep -q "0x8a"; then
    log_success "✅ Besu connection successful"
else
    log_error "❌ Besu connection failed"
    exit 1
fi

# Test Firefly connection
log_warn "Testing Firefly connection..."
if curl -s "$FIREFLY_API_URL/api/v1/status" | grep -q "ready"; then
    log_success "✅ Firefly connection successful"
else
    log_warn "⚠️  Firefly connection failed (may not be deployed)"
fi

# Test Cacti connection
log_warn "Testing Cacti connection..."
if curl -s "$CACTUS_API_URL/api/v1/api-server/healthcheck" | grep -q "status"; then
    log_success "✅ Cacti connection successful"
else
    log_warn "⚠️  Cacti connection failed (may not be deployed)"
fi

# Test Python connectors
log_warn "Testing Python connectors..."
cd "$PROJECT_ROOT"

# Test Besu-Firefly connector
if python3 -c "
import sys
sys.path.insert(0, 'connectors/besu-firefly')
from connector import BesuFireflyConnector
connector = BesuFireflyConnector('$BESU_RPC_URL', '$FIREFLY_API_URL', '')
status = connector.get_besu_status()
print('Besu status:', status)
" 2>/dev/null; then
    log_success "✅ Besu-Firefly connector test successful"
else
    log_warn "⚠️  Besu-Firefly connector test failed (dependencies may be missing)"
fi

# Test Besu-Cacti connector
if python3 -c "
import sys
sys.path.insert(0, 'connectors/besu-cacti')
from connector import BesuCactiConnector
connector = BesuCactiConnector('$BESU_RPC_URL', '$CACTUS_API_URL')
print('Besu-Cacti connector initialized')
" 2>/dev/null; then
    log_success "✅ Besu-Cacti connector test successful"
else
    log_warn "⚠️  Besu-Cacti connector test failed (dependencies may be missing)"
fi

log_success "Connector tests complete!"

