#!/usr/bin/env bash

# Check RPC Status for Chain ID 138
# This script checks if RPC endpoints for Chain ID 138 are live and accessible

set -e


# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

log_info "=== RPC Endpoint Status Check for Chain ID 138 ==="

# Common RPC endpoints for Chain ID 138
RPC_ENDPOINTS=(
    "https://rpc.d-bis.org"
    "https://rpc2.d-bis.org"
    "http://localhost:8545"
)

# Check .env configuration
log_warn "1. Checking .env configuration:"
if [ -f .env ]; then
    RPC_URL=$(grep -E "^RPC_URL=" .env 2>/dev/null | cut -d'=' -f2- | tr -d '"' | tr -d "'" | tr -d ' ' || echo "")
    if [ -n "$RPC_URL" ]; then
        log_success "   ✅ RPC_URL configured: ${RPC_URL}"
        # Add to endpoints list if not already present
        if [[ ! " ${RPC_ENDPOINTS[@]} " =~ " ${RPC_URL} " ]]; then
            RPC_ENDPOINTS+=("$RPC_URL")
        fi
    else
        log_warn "   ⏳ RPC_URL not configured in .env"
    fi
else
    log_warn "   ⏳ .env file not found"
fi

log_warn "2. Testing RPC endpoints:"

# Function to test RPC endpoint
test_rpc_endpoint() {
    local rpc_url=$1
    local timeout=10
    
    log_info "Testing: ${rpc_url}"
    
    # Test 1: Check if endpoint is accessible
    if ! curl -s -X POST "$rpc_url" \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' \
        --max-time $timeout \
        --connect-timeout 5 \
        > /dev/null 2>&1; then
        log_error "   ❌ Not accessible (connection timeout or refused)"
        return 1
    fi
    
    # Test 2: Check chain ID
    CHAIN_ID_RESPONSE=$(curl -s -X POST "$rpc_url" \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' \
        --max-time $timeout \
        --connect-timeout 5 2>/dev/null)
    
    if [ -z "$CHAIN_ID_RESPONSE" ]; then
        log_error "   ❌ No response from endpoint"
        return 1
    fi
    
    CHAIN_ID_HEX=$(echo "$CHAIN_ID_RESPONSE" | grep -oE '"result":"0x[0-9a-f]+"' | cut -d'"' -f4 || echo "")
    if [ -z "$CHAIN_ID_HEX" ]; then
        log_error "   ❌ Invalid response format"
        echo "$CHAIN_ID_RESPONSE" | head -5
        return 1
    fi
    
    # Convert hex to decimal
    CHAIN_ID_DEC=$(printf "%d" "$CHAIN_ID_HEX" 2>/dev/null || echo "0")
    
    if [ "$CHAIN_ID_DEC" = "138" ]; then
        log_success "   ✅ Chain ID: 138 (correct)"
    else
        log_warn "   ⚠️  Chain ID: ${CHAIN_ID_DEC} (expected 138)"
    fi
    
    # Test 3: Check latest block number
    BLOCK_RESPONSE=$(curl -s -X POST "$rpc_url" \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
        --max-time $timeout \
        --connect-timeout 5 2>/dev/null)
    
    BLOCK_HEX=$(echo "$BLOCK_RESPONSE" | grep -oE '"result":"0x[0-9a-f]+"' | cut -d'"' -f4 || echo "")
    if [ -n "$BLOCK_HEX" ]; then
        BLOCK_DEC=$(printf "%d" "$BLOCK_HEX" 2>/dev/null || echo "0")
        log_success "   ✅ Latest block: ${BLOCK_DEC}"
    else
        log_warn "   ⚠️  Could not get block number"
    fi
    
    # Test 4: Check syncing status
    SYNC_RESPONSE=$(curl -s -X POST "$rpc_url" \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' \
        --max-time $timeout \
        --connect-timeout 5 2>/dev/null)
    
    SYNC_STATUS=$(echo "$SYNC_RESPONSE" | grep -oE '"result":(true|false)' | cut -d':' -f2 || echo "")
    if [ "$SYNC_STATUS" = "false" ]; then
        log_success "   ✅ Node is synced"
    elif [ "$SYNC_STATUS" = "true" ]; then
        log_warn "   ⚠️  Node is still syncing"
    else
        log_warn "   ⚠️  Could not check sync status"
    fi
    
    # Test 5: Check peer count (if supported)
    PEER_RESPONSE=$(curl -s -X POST "$rpc_url" \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":1}' \
        --max-time $timeout \
        --connect-timeout 5 2>/dev/null)
    
    PEER_COUNT_HEX=$(echo "$PEER_RESPONSE" | grep -oE '"result":"0x[0-9a-f]+"' | cut -d'"' -f4 || echo "")
    if [ -n "$PEER_COUNT_HEX" ]; then
        PEER_COUNT_DEC=$(printf "%d" "$PEER_COUNT_HEX" 2>/dev/null || echo "0")
        log_success "   ✅ Peer count: ${PEER_COUNT_DEC}"
    fi
    
    return 0
}

# Test each endpoint
LIVE_ENDPOINTS=()
for endpoint in "${RPC_ENDPOINTS[@]}"; do
    if test_rpc_endpoint "$endpoint"; then
        LIVE_ENDPOINTS+=("$endpoint")
    fi
done

# Summary
log_info "=== Summary ==="
if [ ${#LIVE_ENDPOINTS[@]} -gt 0 ]; then
    log_success "✅ ${#LIVE_ENDPOINTS[@]} live endpoint(s) found:"
    for endpoint in "${LIVE_ENDPOINTS[@]}"; do
        log_success "   - ${endpoint}"
    done
else
    log_error "❌ No live endpoints found"
    log_warn "   Please check:"
    echo "   1. Blockchain infrastructure is deployed"
    echo "   2. RPC nodes are running"
    echo "   3. Network connectivity"
    echo "   4. Firewall rules"
fi

log_info "=== Recommendations ==="
if [ ${#LIVE_ENDPOINTS[@]} -eq 0 ]; then
    log_warn "1. Deploy blockchain infrastructure (if not deployed)"
    echo "   See: docs/DEPLOYMENT_ORDER.md"
    log_warn "2. Start local testnet for testing:"
    echo "   ./scripts/deployment/start-local-testnet.sh"
    log_warn "3. Check RPC node status:"
    echo "   kubectl get pods -n besu-network"
    echo "   kubectl logs -f besu-rpc-0 -n besu-network"
else
    log_success "✅ RPC endpoints are live and accessible"
    log_success "   You can now deploy contracts using:"
    echo "   ./scripts/deployment/deploy-all-ordered.sh"
fi


