#!/usr/bin/env bash
# Check mempool and block production status
# Usage: ./check-mempool-status.sh

set -uo 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}"
DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo "========================================="
echo "Mempool & Block Production Status"
echo "========================================="
echo ""

# Check block production
log_info "Checking block production..."
BLOCK1=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
sleep 3
BLOCK2=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

if [ "$BLOCK2" -gt "$BLOCK1" ]; then
    log_success "✓ Blocks are being produced ($BLOCK1 -> $BLOCK2)"
    BLOCK_RATE=$((BLOCK2 - BLOCK1))
    echo "   Block rate: ~$BLOCK_RATE blocks in 3 seconds"
else
    log_warn "⚠ Blocks may not be progressing"
fi

echo ""

# Check recent block transaction counts
log_info "Checking recent block transaction counts..."
LATEST=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
EMPTY_BLOCKS=0
TOTAL_TXS=0

for i in $(seq $((LATEST - 9)) $LATEST); do
    TX_COUNT=$(cast block $i --rpc-url "$RPC_URL" --json 2>/dev/null | jq -r '.transactions | length' 2>/dev/null || echo "0")
    if [ "$TX_COUNT" = "0" ]; then
        ((EMPTY_BLOCKS++))
    else
        TOTAL_TXS=$((TOTAL_TXS + TX_COUNT))
    fi
done

echo "   Last 10 blocks: $EMPTY_BLOCKS empty, $TOTAL_TXS total transactions"
if [ "$EMPTY_BLOCKS" -eq 10 ]; then
    log_warn "⚠ All recent blocks are empty - transactions not being mined"
elif [ "$TOTAL_TXS" -gt 0 ]; then
    log_success "✓ Some transactions are being mined"
fi

echo ""

# Check deployer nonce
if [ -n "$DEPLOYER" ]; then
    log_info "Checking deployer transaction status..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    echo "   Current nonce: $CURRENT_NONCE"
    
    # Check if any transactions from deployer in recent blocks
    FOUND_TXS=0
    for i in $(seq $((LATEST - 20)) $LATEST); do
        TX_COUNT=$(cast block $i --rpc-url "$RPC_URL" --json 2>/dev/null | jq -r ".transactions[] | select(.from == \"$DEPLOYER\") | .nonce" 2>/dev/null | wc -l)
        if [ "$TX_COUNT" -gt 0 ]; then
            FOUND_TXS=$((FOUND_TXS + TX_COUNT))
        fi
    done
    
    if [ "$FOUND_TXS" -gt 0 ]; then
        log_success "✓ Found $FOUND_TXS transactions from deployer in last 20 blocks"
    else
        log_warn "⚠ No transactions from deployer in last 20 blocks"
        echo "   This suggests transactions are stuck in mempool"
    fi
fi

echo ""

# Summary
echo "========================================="
echo "Summary"
echo "========================================="
echo ""

if [ "$BLOCK2" -gt "$BLOCK1" ] && [ "$EMPTY_BLOCKS" -lt 10 ]; then
    log_success "✅ Network is healthy - blocks being produced and transactions mined"
elif [ "$BLOCK2" -gt "$BLOCK1" ] && [ "$EMPTY_BLOCKS" -eq 10 ]; then
    log_warn "⚠️ Blocks are being produced but transactions are NOT being mined"
    echo ""
    echo "Possible causes:"
    echo "  1. Transactions in mempool are invalid/reverting"
    echo "  2. Validators are rejecting transactions"
    echo "  3. Gas price issues"
    echo "  4. Mempool not being processed"
    echo ""
    echo "Recommendation: Check Besu logs for transaction rejection reasons"
else
    log_error "✗ Network may not be producing blocks properly"
fi

echo ""

