#!/usr/bin/env bash
# Comprehensive script to resolve Ethereum Mainnet configuration issue
# This script handles the mempool blocking issue
# Usage: ./resolve-ethereum-mainnet-config.sh

set -uo 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'
CYAN='\033[0;36m'
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"; }
log_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

source "$SOURCE_PROJECT/.env"

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-0xe0E93247376aa097dB308B92e6Ba36bA015535D0}"

ETHEREUM_MAINNET_SELECTOR="5009297550715157269"
WETH9_MAINNET_BRIDGE="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
WETH10_MAINNET_BRIDGE="0x105f8a15b819948a89153505762444ee9f324684"

DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)

log_info "========================================="
log_info "Resolve Ethereum Mainnet Configuration"
log_info "========================================="
log_info ""

# Step 1: Check current state
log_step "Step 1: Checking current configuration..."
WETH9_CHECK=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_CHECK=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

if [ -n "$WETH9_CHECK" ] && ! echo "$WETH9_CHECK" | grep -qE "^0x0+$" && ! echo "$WETH9_CHECK" | grep -qE "^0x0000000000000000000000000000000000000000$"; then
    log_success "✓ WETH9 bridge already configured"
    WETH9_CONFIGURED=true
else
    log_warn "⚠ WETH9 bridge not configured"
    WETH9_CONFIGURED=false
fi

if [ -n "$WETH10_CHECK" ] && ! echo "$WETH10_CHECK" | grep -qE "^0x0+$" && ! echo "$WETH10_CHECK" | grep -qE "^0x0000000000000000000000000000000000000000$"; then
    log_success "✓ WETH10 bridge already configured"
    WETH10_CONFIGURED=true
else
    log_warn "⚠ WETH10 bridge not configured"
    WETH10_CONFIGURED=false
fi

if [ "$WETH9_CONFIGURED" = true ] && [ "$WETH10_CONFIGURED" = true ]; then
    log_success "✓ Ethereum Mainnet is already configured!"
    exit 0
fi

log_info ""

# Step 2: Check nonce and wait for pending transactions
log_step "Step 2: Checking for pending transactions..."
CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
log_info "Current nonce: $CURRENT_NONCE"

# Wait a bit for any pending transactions to clear
log_info "Waiting 30 seconds for pending transactions to clear..."
sleep 30

NEW_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
if [ "$NEW_NONCE" -gt "$CURRENT_NONCE" ]; then
    log_success "✓ Transactions processed (nonce advanced from $CURRENT_NONCE to $NEW_NONCE)"
    CURRENT_NONCE=$NEW_NONCE
else
    log_warn "⚠ No transactions processed (nonce still $CURRENT_NONCE)"
fi

log_info ""

# Step 3: Try configuration with multiple gas price strategies
log_step "Step 3: Attempting configuration..."

configure_bridge() {
    local bridge_addr="$1"
    local bridge_name="$2"
    local current_nonce="$3"
    
    log_info "Configuring $bridge_name bridge..."
    
    # Strategy 1: Use current gas price * 100
    CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    HIGH_GAS=$(echo "$CURRENT_GAS * 100" | bc 2>/dev/null || echo "100000000000")
    
    log_info "Attempting with gas price: $HIGH_GAS wei ($(echo "scale=2; $HIGH_GAS / 1000000000" | bc) gwei)"
    
    TX_OUTPUT=$(cast send "$bridge_addr" \
        "addDestination(uint64,address)" \
        "$ETHEREUM_MAINNET_SELECTOR" \
        "$(if [ "$bridge_name" = "WETH9" ]; then echo "$WETH9_MAINNET_BRIDGE"; else echo "$WETH10_MAINNET_BRIDGE"; fi)" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "$HIGH_GAS" \
        --gas-limit 200000 \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "transactionHash|Success"; then
        HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
        log_success "✓ $bridge_name bridge configured: $HASH"
        return 0
    elif echo "$TX_OUTPUT" | grep -q "Replacement transaction underpriced"; then
        log_warn "⚠ Still blocked by mempool. Trying with even higher gas..."
        
        # Strategy 2: Use extremely high gas price
        EXTREME_GAS="100000000000000"  # 100,000 gwei
        TX_OUTPUT=$(cast send "$bridge_addr" \
            "addDestination(uint64,address)" \
            "$ETHEREUM_MAINNET_SELECTOR" \
            "$(if [ "$bridge_name" = "WETH9" ]; then echo "$WETH9_MAINNET_BRIDGE"; else echo "$WETH10_MAINNET_BRIDGE"; fi)" \
            --rpc-url "$RPC_URL" \
            --private-key "$PRIVATE_KEY" \
            --gas-price "$EXTREME_GAS" \
            --gas-limit 200000 \
            2>&1 || echo "FAILED")
        
        if echo "$TX_OUTPUT" | grep -qE "transactionHash|Success"; then
            HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
            log_success "✓ $bridge_name bridge configured: $HASH"
            return 0
        else
            log_error "✗ $bridge_name configuration failed - mempool still blocking"
            return 1
        fi
    else
        ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted" | head -1 || echo "Unknown")
        log_error "✗ $bridge_name configuration failed: $ERR"
        return 1
    fi
}

# Configure WETH9 if needed
if [ "$WETH9_CONFIGURED" = false ]; then
    configure_bridge "$WETH9_BRIDGE" "WETH9" "$CURRENT_NONCE"
    sleep 10
    ((CURRENT_NONCE++))
fi

# Configure WETH10 if needed
if [ "$WETH10_CONFIGURED" = false ]; then
    configure_bridge "$WETH10_BRIDGE" "WETH10" "$CURRENT_NONCE"
    sleep 10
fi

log_info ""

# Step 4: Verify final configuration
log_step "Step 4: Verifying final configuration..."
sleep 10

WETH9_FINAL=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_FINAL=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

log_info ""
log_success "========================================="
log_success "Configuration Verification"
log_success "========================================="
log_info ""

if [ -n "$WETH9_FINAL" ] && ! echo "$WETH9_FINAL" | grep -qE "^0x0+$" && ! echo "$WETH9_FINAL" | grep -qE "^0x0000000000000000000000000000000000000000$"; then
    log_success "✓ WETH9 bridge: CONFIGURED"
else
    log_error "✗ WETH9 bridge: NOT CONFIGURED"
fi

if [ -n "$WETH10_FINAL" ] && ! echo "$WETH10_FINAL" | grep -qE "^0x0+$" && ! echo "$WETH10_FINAL" | grep -qE "^0x0000000000000000000000000000000000000000$"; then
    log_success "✓ WETH10 bridge: CONFIGURED"
else
    log_error "✗ WETH10 bridge: NOT CONFIGURED"
fi

log_info ""

if [ -n "$WETH9_FINAL" ] && ! echo "$WETH9_FINAL" | grep -qE "^0x0+$" && [ -n "$WETH10_FINAL" ] && ! echo "$WETH10_FINAL" | grep -qE "^0x0+$"; then
    log_success "✅ Ethereum Mainnet configuration complete!"
    log_info ""
    log_info "Next step: Run test to verify:"
    log_info "  ./scripts/test-bridge-all-7-networks.sh weth9"
else
    log_warn "⚠ Configuration incomplete. If mempool is still blocking:"
    log_info "  1. Restart Besu node to clear mempool"
    log_info "  2. Or wait longer for pending transactions to process"
    log_info "  3. Or use a different account to configure"
fi
log_info ""

