#!/usr/bin/env bash
# Network status and latency monitoring
# Usage: ./network-monitoring.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

source "$SOURCE_PROJECT/.env" 2>/dev/null || true

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"

# Measure RPC latency
measure_latency() {
    local rpc_url="$1"
    local start=$(date +%s%N)
    cast block-number --rpc-url "$rpc_url" >/dev/null 2>&1
    local end=$(date +%s%N)
    local latency=$(( (end - start) / 1000000 ))  # Convert to milliseconds
    echo "$latency"
}

# Check network status
check_network_status() {
    echo "=== Network Status ==="
    echo ""
    
    # Block number
    BLOCK_NUMBER=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "N/A")
    echo "Current Block: $BLOCK_NUMBER"
    
    # Latency
    LATENCY=$(measure_latency "$RPC_URL")
    echo "RPC Latency: ${LATENCY}ms"
    
    # Gas price
    GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    GAS_GWEI=$(echo "scale=2; $GAS_PRICE / 1000000000" | bc 2>/dev/null || echo "0")
    echo "Gas Price: $GAS_GWEI gwei"
    
    # Network health
    if [ "$LATENCY" -lt 1000 ]; then
        echo "Network Status: ✅ Healthy"
    elif [ "$LATENCY" -lt 5000 ]; then
        echo "Network Status: ⚠️  Degraded"
    else
        echo "Network Status: ❌ Poor"
    fi
}

check_network_status

