#!/bin/bash

set -e

# Health check script for DeFi Oracle Meta Mainnet

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

echo "Health Check for DeFi Oracle Meta Mainnet"
echo "=========================================="
echo ""

# Check RPC endpoint
echo "1. Checking RPC endpoint..."
BLOCK_NUMBER=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
  | jq -r '.result')

if [ -z "$BLOCK_NUMBER" ] || [ "$BLOCK_NUMBER" = "null" ]; then
    echo "   ❌ RPC endpoint is not responding"
    exit 1
else
    echo "   ✅ RPC endpoint is responding (Block: $BLOCK_NUMBER)"
fi

# Check chain ID
echo "2. Checking Chain ID..."
CHAIN_ID=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"net_version","params":[],"id":1}' \
  | jq -r '.result')

if [ "$CHAIN_ID" != "138" ]; then
    echo "   ❌ Chain ID mismatch (Expected: 138, Got: $CHAIN_ID)"
    exit 1
else
    echo "   ✅ Chain ID is correct (138)"
fi

# Check block production
echo "3. Checking block production..."
CURRENT_BLOCK=$(printf "%d" "$BLOCK_NUMBER")
sleep 5
NEW_BLOCK=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
  | jq -r '.result')
NEW_BLOCK_DECIMAL=$(printf "%d" "$NEW_BLOCK")

if [ "$NEW_BLOCK_DECIMAL" -le "$CURRENT_BLOCK" ]; then
    echo "   ❌ Block production appears stalled"
    exit 1
else
    echo "   ✅ Block production is working (Block: $NEW_BLOCK)"
fi

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

if [ "$SYNCING" != "false" ]; then
    echo "   ⚠️  Node is still syncing"
else
    echo "   ✅ Node is fully synced"
fi

# Check peer count
echo "5. Checking peer count..."
PEER_COUNT=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":1}' \
  | jq -r '.result')
PEER_COUNT_DECIMAL=$(printf "%d" "$PEER_COUNT")

if [ "$PEER_COUNT_DECIMAL" -lt 1 ]; then
    echo "   ⚠️  Low peer count ($PEER_COUNT_DECIMAL)"
else
    echo "   ✅ Peer count is healthy ($PEER_COUNT_DECIMAL peers)"
fi

# Check explorer (if available)
if [ -n "$EXPLORER_URL" ]; then
    echo "6. Checking explorer..."
    EXPLORER_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$EXPLORER_URL")
    if [ "$EXPLORER_STATUS" = "200" ]; then
        echo "   ✅ Explorer is accessible"
    else
        echo "   ⚠️  Explorer is not accessible (Status: $EXPLORER_STATUS)"
    fi
fi

echo ""
echo "Health check complete!"

