#!/usr/bin/env bash
# Wait for nonce to advance, then configure Ethereum Mainnet
# This script monitors the nonce and automatically configures when ready
# Usage: ./wait-and-configure-ethereum-mainnet.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}"
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 || echo "")

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

log_info "========================================="
log_info "Wait and Configure Ethereum Mainnet"
log_info "========================================="
log_info ""
log_info "Deployer: $DEPLOYER"
log_info "RPC URL: $RPC_URL"
log_info ""

# Function to check if we can send transaction
can_send_transaction() {
    local nonce=$1
    local gas_price=$2
    
    # Try a test transaction (will fail but tells us if nonce is available)
    local result=$(cast send "$WETH9_BRIDGE" \
        "addDestination(uint64,address)" \
        "$ETHEREUM_MAINNET_SELECTOR" \
        "$WETH9_MAINNET_BRIDGE" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "$gas_price" \
        --nonce "$nonce" \
        --gas-limit 200000 \
        2>&1 || echo "ERROR")
    
    if echo "$result" | grep -qE "transactionHash|Success"; then
        return 0  # Success
    elif echo "$result" | grep -q "Replacement transaction underpriced"; then
        return 1  # Still blocked
    elif echo "$result" | grep -q "Known transaction"; then
        return 1  # Transaction exists
    else
        return 2  # Other error
    fi
}

# Function to configure bridges
configure_bridges() {
    local nonce=$1
    local gas_price=$2
    
    log_info "Configuring with nonce $nonce, gas price $gas_price wei"
    
    # Configure WETH9
    log_info "Configuring WETH9 bridge..."
    local tx1=$(cast send "$WETH9_BRIDGE" \
        "addDestination(uint64,address)" \
        "$ETHEREUM_MAINNET_SELECTOR" \
        "$WETH9_MAINNET_BRIDGE" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "$gas_price" \
        --nonce "$nonce" \
        --gas-limit 200000 \
        2>&1 || echo "FAILED")
    
    if echo "$tx1" | grep -qE "transactionHash|Success"; then
        local hash1=$(echo "$tx1" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
        log_success "✓ WETH9 bridge configured: $hash1"
        sleep 10
        
        # Configure WETH10
        local next_nonce=$((nonce + 1))
        log_info "Configuring WETH10 bridge with nonce $next_nonce..."
        local tx2=$(cast send "$WETH10_BRIDGE" \
            "addDestination(uint64,address)" \
            "$ETHEREUM_MAINNET_SELECTOR" \
            "$WETH10_MAINNET_BRIDGE" \
            --rpc-url "$RPC_URL" \
            --private-key "$PRIVATE_KEY" \
            --gas-price "$gas_price" \
            --nonce "$next_nonce" \
            --gas-limit 200000 \
            2>&1 || echo "FAILED")
        
        if echo "$tx2" | grep -qE "transactionHash|Success"; then
            local hash2=$(echo "$tx2" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
            log_success "✓ WETH10 bridge configured: $hash2"
            return 0
        else
            log_error "✗ WETH10 configuration failed"
            return 1
        fi
    else
        log_error "✗ WETH9 configuration failed"
        return 1
    fi
}

# Get initial nonce
INITIAL_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
log_info "Initial nonce: $INITIAL_NONCE"
log_info ""

# Wait for nonce to be available
log_info "Waiting for nonce to be available for transaction..."
log_info "This may take a few minutes as pending transactions process..."
log_info ""

MAX_WAIT=3600  # 1 hour max
CHECK_INTERVAL=30  # Check every 30 seconds
elapsed=0
attempts=0

while [ $elapsed -lt $MAX_WAIT ]; do
    attempts=$((attempts + 1))
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    if [ "$CURRENT_NONCE" != "$INITIAL_NONCE" ]; then
        log_success "✓ Nonce advanced from $INITIAL_NONCE to $CURRENT_NONCE"
        INITIAL_NONCE=$CURRENT_NONCE
    fi
    
    log_info "[Attempt $attempts] Current nonce: $CURRENT_NONCE (elapsed: ${elapsed}s)"
    
    # Try with current nonce and high gas price
    GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000")
    HIGH_GAS=$(echo "$GAS_PRICE * 1000" | bc 2>/dev/null || echo "1000000")
    
    can_send_result=$(can_send_transaction "$CURRENT_NONCE" "$HIGH_GAS" 2>&1 || echo "ERROR")
    
    if echo "$can_send_result" | grep -qE "transactionHash|Success"; then
        log_success "✓ Nonce $CURRENT_NONCE is available!"
        log_info "Attempting configuration..."
        
        if configure_bridges "$CURRENT_NONCE" "$HIGH_GAS"; then
            log_success ""
            log_success "========================================="
            log_success "✅ Ethereum Mainnet Configuration Complete!"
            log_success "========================================="
            log_info ""
            log_info "Verifying configuration..."
            sleep 5
            
            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+$" && [ -n "$WETH10_CHECK" ] && ! echo "$WETH10_CHECK" | grep -qE "^0x0+$"; then
                log_success "✅ Configuration verified!"
                log_info ""
                log_info "Run test to verify:"
                log_info "  ./scripts/test-bridge-all-7-networks.sh weth9"
                exit 0
            else
                log_warn "⚠ Configuration may not be complete"
            fi
            exit 0
        fi
    elif echo "$can_send_result" | grep -q "Replacement transaction underpriced"; then
        log_warn "⚠ Nonce $CURRENT_NONCE still blocked (pending transaction with higher gas price)"
    elif echo "$can_send_result" | grep -q "Known transaction"; then
        log_warn "⚠ Nonce $CURRENT_NONCE has existing transaction"
    else
        log_warn "⚠ Nonce $CURRENT_NONCE not available: $(echo "$can_send_result" | head -1)"
    fi
    
    sleep $CHECK_INTERVAL
    elapsed=$((elapsed + CHECK_INTERVAL))
done

log_error "✗ Timeout: Could not configure Ethereum Mainnet after $MAX_WAIT seconds"
log_info ""
log_info "The pending transactions in validator pools are taking longer than expected to process."
log_info ""
log_info "Options:"
log_info "  1. Wait longer and run this script again"
log_info "  2. Use new account: ./scripts/configure-ethereum-mainnet-with-new-account.sh"
log_info "  3. Check validator logs for transaction status"
log_info ""
exit 1

