#!/bin/bash

# Test RPC endpoint connectivity and ChainID 138

set -e

RPC_URL="${RPC_URL:-http://localhost:8545}"

echo "Testing RPC endpoint: $RPC_URL"
echo "================================"
echo ""

# Test 1: Check if RPC endpoint is reachable
echo "1. Testing RPC endpoint connectivity..."
RESPONSE=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}')

if [ -z "$RESPONSE" ] || echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
    echo "   ❌ RPC endpoint is not responding or returned an error"
    echo "   Response: $RESPONSE"
    exit 1
else
    echo "   ✅ RPC endpoint is responding"
fi

# Test 2: Check ChainID
echo "2. Testing ChainID..."
CHAIN_ID_RESPONSE=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}')

CHAIN_ID=$(echo "$CHAIN_ID_RESPONSE" | jq -r '.result')
CHAIN_ID_DECIMAL=$(printf "%d" "$CHAIN_ID")

if [ "$CHAIN_ID_DECIMAL" != "138" ]; then
    echo "   ❌ ChainID mismatch! Expected 138, got $CHAIN_ID_DECIMAL"
    exit 1
else
    echo "   ✅ ChainID is correct (138 / $CHAIN_ID)"
fi

# Test 3: Get block number
echo "3. Getting current block number..."
BLOCK_NUMBER_RESPONSE=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}')

BLOCK_NUMBER=$(echo "$BLOCK_NUMBER_RESPONSE" | jq -r '.result')
BLOCK_NUMBER_DECIMAL=$(printf "%d" "$BLOCK_NUMBER")
echo "   ✅ Current block: $BLOCK_NUMBER_DECIMAL ($BLOCK_NUMBER)"

# Test 4: Get gas price
echo "4. Getting gas price..."
GAS_PRICE_RESPONSE=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}')

GAS_PRICE=$(echo "$GAS_PRICE_RESPONSE" | jq -r '.result')
echo "   ✅ Gas price: $GAS_PRICE"

# Test 5: Get peer count
echo "5. Getting peer count..."
PEER_COUNT_RESPONSE=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":1}')

PEER_COUNT=$(echo "$PEER_COUNT_RESPONSE" | jq -r '.result')
PEER_COUNT_DECIMAL=$(printf "%d" "$PEER_COUNT")
echo "   ✅ Peer count: $PEER_COUNT_DECIMAL"

# Test 6: Check sync status
echo "6. Checking sync status..."
SYNC_RESPONSE=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}')

SYNC_STATUS=$(echo "$SYNC_RESPONSE" | jq -r '.result')
if [ "$SYNC_STATUS" = "false" ]; then
    echo "   ✅ Node is fully synced"
else
    echo "   ⚠️  Node is still syncing: $SYNC_STATUS"
fi

echo ""
echo "================================"
echo "✅ All RPC tests passed!"
echo "================================"
echo ""
echo "RPC endpoint is ready for Tatum SDK integration"
echo "ChainID: 138 ($CHAIN_ID)"
echo "Current Block: $BLOCK_NUMBER_DECIMAL"

