#!/usr/bin/env bash
# Configure Ethereum Mainnet with High Gas Price
# Attempts to replace stuck transaction with very high gas price
# Usage: ./configure-ethereum-mainnet-with-high-gas.sh [gas_price_gwei]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/ccip-destinations.sh"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"

# 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_explorer_runtime_env

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

if [ -z "$PRIVATE_KEY" ]; then
    log_error "PRIVATE_KEY not available in effective environment"
    exit 1
fi

# Gas price (default: 50 gwei, or from argument)
GAS_PRICE_GWEI="${1:-50}"
GAS_PRICE_WEI=$(echo "$GAS_PRICE_GWEI * 1000000000" | bc 2>/dev/null || echo "50000000000")

# Ethereum Mainnet configuration
ETHEREUM_MAINNET_SELECTOR="${ETHEREUM_MAINNET_SELECTOR:-$(ccip_destination_selector_by_name "Ethereum Mainnet")}"
WETH9_MAINNET_BRIDGE="0x2A0840e5117683b11682ac46f5CF5621E67269E3"
WETH10_MAINNET_BRIDGE="0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03"

# Bridge addresses on ChainID 138
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

log_info "========================================="
log_info "Configure Ethereum Mainnet (High Gas)"
log_info "========================================="
log_info ""
log_info "Gas Price: $GAS_PRICE_GWEI gwei ($GAS_PRICE_WEI wei)"
log_info "Ethereum Mainnet Selector: $ETHEREUM_MAINNET_SELECTOR"
log_info ""

# Get account and nonce
ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$ACCOUNT" ]; then
    log_error "Could not derive address from private key"
    exit 1
fi

CURRENT_NONCE=$(cast nonce "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
log_info "Account: $ACCOUNT"
log_info "Current Nonce: $CURRENT_NONCE"
log_info ""

# Configure WETH9 Bridge
log_info "Configuring WETH9 Bridge..."
TX_OUTPUT=$(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_WEI" \
    --nonce "$CURRENT_NONCE" \
    2>&1 || echo "FAILED")

if echo "$TX_OUTPUT" | grep -qE "(blockHash|transactionHash)"; then
    TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "(blockHash|transactionHash)[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' | head -1)
    log_success "WETH9 Bridge: Transaction sent: $TX_HASH"
    ((CURRENT_NONCE++)) || true
else
    log_error "WETH9 Bridge: Transaction failed"
    log_error "$TX_OUTPUT"
    if echo "$TX_OUTPUT" | grep -q "underpriced"; then
        log_warn "Try with even higher gas price: $0 $((GAS_PRICE_GWEI * 2))"
    fi
fi

# Configure WETH10 Bridge
log_info ""
log_info "Configuring WETH10 Bridge..."
TX_OUTPUT=$(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_WEI" \
    --nonce "$CURRENT_NONCE" \
    2>&1 || echo "FAILED")

if echo "$TX_OUTPUT" | grep -qE "(blockHash|transactionHash)"; then
    TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "(blockHash|transactionHash)[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' | head -1)
    log_success "WETH10 Bridge: Transaction sent: $TX_HASH"
else
    log_error "WETH10 Bridge: Transaction failed"
    log_error "$TX_OUTPUT"
    if echo "$TX_OUTPUT" | grep -q "underpriced"; then
        log_warn "Try with even higher gas price: $0 $((GAS_PRICE_GWEI * 2))"
    fi
fi

# Verify after delay
log_info ""
log_info "Waiting for transactions to be mined..."
sleep 10

log_info ""
log_info "Verifying configuration..."
"$SCRIPT_DIR/check-bridge-config.sh" | grep -A 20 "Ethereum"

log_info ""
log_info "========================================="
log_info "Configuration Complete"
log_info "========================================="
