#!/usr/bin/env bash
# Resolve stuck transaction using Besu QBFT admin methods
# This script uses Besu-specific RPC methods to clear stuck transactions
# Usage: ./resolve-stuck-transaction-besu-qbft.sh

set -euo pipefail

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
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"; }

# Load environment variables
if [ -f "$SOURCE_PROJECT/.env" ]; then
    source "$SOURCE_PROJECT/.env"
else
    log_error ".env file not found in $SOURCE_PROJECT"
    exit 1
fi

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")

if [ -z "$DEPLOYER" ]; then
    log_error "Failed to get deployer address"
    exit 1
fi

log_info "========================================="
log_info "Resolve Stuck Transaction (Besu QBFT)"
log_info "========================================="
log_info ""
log_info "RPC URL: $RPC_URL"
log_info "Deployer: $DEPLOYER"
log_info ""

# Step 1: Check current RPC modules
log_info "Step 1: Checking available RPC modules..."
RPC_MODULES=$(curl -s -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"rpc_modules","params":[],"id":1}' \
    "$RPC_URL" 2>/dev/null || echo "")

if [ -z "$RPC_MODULES" ]; then
    log_error "Failed to connect to RPC"
    exit 1
fi

AVAILABLE_MODULES=$(echo "$RPC_MODULES" | jq -r '.result | keys[]' 2>/dev/null || echo "")
log_info "Available modules: $AVAILABLE_MODULES"

# Check if TXPOOL is enabled
if echo "$AVAILABLE_MODULES" | grep -qi "txpool"; then
    log_success "✓ TXPOOL module is enabled"
    TXPOOL_ENABLED=true
else
    log_warn "⚠ TXPOOL module is NOT enabled"
    TXPOOL_ENABLED=false
fi

# Check if ADMIN is enabled
if echo "$AVAILABLE_MODULES" | grep -qi "admin"; then
    log_success "✓ ADMIN module is enabled"
    ADMIN_ENABLED=true
else
    log_warn "⚠ ADMIN module is NOT enabled"
    ADMIN_ENABLED=false
fi

log_info ""

# Step 2: Try to inspect transaction pool (if TXPOOL enabled)
if [ "$TXPOOL_ENABLED" = true ]; then
    log_info "Step 2: Inspecting transaction pool..."
    
    # Try txpool_status
    TXPOOL_STATUS=$(curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"txpool_status","params":[],"id":1}' \
        "$RPC_URL" 2>/dev/null || echo "")
    
    if [ -n "$TXPOOL_STATUS" ] && echo "$TXPOOL_STATUS" | jq -e '.result' >/dev/null 2>&1; then
        PENDING=$(echo "$TXPOOL_STATUS" | jq -r '.result.pending // 0' 2>/dev/null || echo "0")
        QUEUED=$(echo "$TXPOOL_STATUS" | jq -r '.result.queued // 0' 2>/dev/null || echo "0")
        log_info "Pending transactions: $PENDING"
        log_info "Queued transactions: $QUEUED"
        
        if [ "$PENDING" != "0" ] || [ "$QUEUED" != "0" ]; then
            log_warn "⚠ Transaction pool has pending/queued transactions"
        fi
    else
        log_warn "⚠ Could not get transaction pool status"
    fi
    
    # Try txpool_content to find deployer's transactions
    log_info "Checking for deployer transactions in pool..."
    TXPOOL_CONTENT=$(curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"txpool_content","params":[],"id":1}' \
        "$RPC_URL" 2>/dev/null || echo "")
    
    if [ -n "$TXPOOL_CONTENT" ] && echo "$TXPOOL_CONTENT" | jq -e ".result.pending.\"$DEPLOYER\"" >/dev/null 2>&1; then
        DEPLOYER_TXS=$(echo "$TXPOOL_CONTENT" | jq -r ".result.pending.\"$DEPLOYER\" // {}" 2>/dev/null)
        if [ "$DEPLOYER_TXS" != "{}" ] && [ "$DEPLOYER_TXS" != "null" ]; then
            log_warn "⚠ Found transactions for deployer in pool:"
            echo "$DEPLOYER_TXS" | jq '.' 2>/dev/null || echo "$DEPLOYER_TXS"
        else
            log_info "No transactions found for deployer in pool"
        fi
    fi
    
    log_info ""
fi

# Step 3: Get current nonce
log_info "Step 3: Checking current nonce..."
CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
log_info "Current nonce: $CURRENT_NONCE"

# Step 4: Try to clear transaction pool using various methods
log_info ""
log_info "Step 4: Attempting to clear stuck transaction..."

# Method 1: txpool_besuClear (Besu-specific)
if [ "$TXPOOL_ENABLED" = true ]; then
    log_info "Trying txpool_besuClear..."
    CLEAR_RESULT=$(curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"txpool_besuClear","params":[],"id":1}' \
        "$RPC_URL" 2>/dev/null || echo "")
    
    if echo "$CLEAR_RESULT" | jq -e '.result == true' >/dev/null 2>&1; then
        log_success "✓ Transaction pool cleared using txpool_besuClear"
        POOL_CLEARED=true
    elif echo "$CLEAR_RESULT" | jq -e '.error' >/dev/null 2>&1; then
        ERROR_MSG=$(echo "$CLEAR_RESULT" | jq -r '.error.message // "Unknown error"' 2>/dev/null || echo "Unknown")
        log_warn "⚠ txpool_besuClear failed: $ERROR_MSG"
        POOL_CLEARED=false
    else
        log_warn "⚠ txpool_besuClear returned unexpected result"
        POOL_CLEARED=false
    fi
else
    log_warn "⚠ TXPOOL not enabled, skipping txpool_besuClear"
    POOL_CLEARED=false
fi

# Method 2: txpool_clear (alternative)
if [ "$TXPOOL_ENABLED" = true ] && [ "$POOL_CLEARED" != "true" ]; then
    log_info "Trying txpool_clear..."
    CLEAR_RESULT=$(curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"txpool_clear","params":[],"id":1}' \
        "$RPC_URL" 2>/dev/null || echo "")
    
    if echo "$CLEAR_RESULT" | jq -e '.result == true' >/dev/null 2>&1; then
        log_success "✓ Transaction pool cleared using txpool_clear"
        POOL_CLEARED=true
    elif echo "$CLEAR_RESULT" | jq -e '.error' >/dev/null 2>&1; then
        ERROR_MSG=$(echo "$CLEAR_RESULT" | jq -r '.error.message // "Unknown error"' 2>/dev/null || echo "Unknown")
        log_warn "⚠ txpool_clear failed: $ERROR_MSG"
    fi
fi

# Method 3: admin_removeTransaction (if ADMIN enabled)
if [ "$ADMIN_ENABLED" = true ] && [ "$POOL_CLEARED" != "true" ]; then
    log_info "Trying admin_removeTransaction (need transaction hash)..."
    log_warn "⚠ admin_removeTransaction requires transaction hash - cannot use without hash"
fi

# Method 4: Enable TXPOOL if not enabled and retry
if [ "$TXPOOL_ENABLED" = false ]; then
    log_info ""
    log_warn "⚠ TXPOOL module is not enabled on RPC node"
    log_info "To enable TXPOOL, add to RPC config:"
    log_info "  rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"TXPOOL\"]"
    log_info ""
    log_info "Then restart the Besu RPC service and run this script again"
fi

log_info ""

# Step 5: Verify nonce after clearing
if [ "$POOL_CLEARED" = true ]; then
    log_info "Step 5: Verifying nonce after clearing..."
    sleep 2
    NEW_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    log_info "Nonce after clearing: $NEW_NONCE"
    
    if [ "$NEW_NONCE" != "$CURRENT_NONCE" ]; then
        log_success "✓ Nonce changed - transaction may have been processed"
    else
        log_info "Nonce unchanged - transaction may still be stuck"
    fi
fi

log_info ""
log_success "========================================="
log_success "Resolution Attempt Complete"
log_success "========================================="
log_info ""

if [ "$POOL_CLEARED" = true ]; then
    log_success "✅ Transaction pool cleared successfully"
    log_info ""
    log_info "Next steps:"
    log_info "  1. Wait 5-10 seconds for state to update"
    log_info "  2. Run: ./scripts/configure-ethereum-mainnet-final.sh"
else
    log_warn "⚠ Could not clear transaction pool automatically"
    log_info ""
    log_info "Alternative solutions:"
    log_info "  1. Enable TXPOOL on RPC node and retry"
    log_info "  2. Restart Besu RPC node (clears mempool)"
    log_info "  3. Use a different deployer account"
    log_info "  4. Wait for transaction retention period to expire"
fi

log_info ""

