#!/usr/bin/env bash
# Configure Ethereum Mainnet destination for both bridges
# Usage: ./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"
# Using same addresses as other chains (these should be deployed on Ethereum Mainnet)
WETH9_MAINNET_BRIDGE="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
WETH10_MAINNET_BRIDGE="0x105f8a15b819948a89153505762444ee9f324684"

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not set in .env file"
    exit 1
fi

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 "Configure Ethereum Mainnet Destination"
log_info "========================================="
log_info ""
log_info "Ethereum Mainnet Selector: $ETHEREUM_MAINNET_SELECTOR"
log_info "WETH9 Mainnet Bridge: $WETH9_MAINNET_BRIDGE"
log_info "WETH10 Mainnet Bridge: $WETH10_MAINNET_BRIDGE"
log_info "Deployer: $DEPLOYER"
log_info ""

# Check current configuration
log_info "Checking current configuration..."

WETH9_CHECK=$(timeout 10 cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_CHECK=$(timeout 10 cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

# Configure WETH9 Bridge
if [ -n "$WETH9_CHECK" ] && ! echo "$WETH9_CHECK" | grep -qE "^0x0+$" && ! echo "$WETH9_CHECK" | grep -qE "^0x0000000000000000000000000000000000000000$"; then
    log_success "✓ WETH9 bridge already configured for Ethereum Mainnet"
    log_detail "Current destination: $WETH9_CHECK"
else
    log_info "Configuring WETH9 bridge for Ethereum Mainnet..."
    log_info "Waiting for any pending transactions to clear..."
    sleep 15
    
    # Get current gas price and use 10x to ensure replacement
    CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    REPLACEMENT_GAS=$(echo "$CURRENT_GAS * 10" | bc 2>/dev/null || echo "100000000000")
    
    # Try with very high gas price to replace any pending transactions
    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 "$REPLACEMENT_GAS" \
        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 "✓ WETH9 bridge configured: $HASH"
        sleep 5
    else
        ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted|already exists" | head -1 || echo "Unknown")
        if echo "$ERR" | grep -q "already exists"; then
            log_success "✓ WETH9 bridge already configured for Ethereum Mainnet"
        else
            log_error "✗ WETH9 configuration failed: $ERR"
            log_info "Full output: $TX_OUTPUT"
        fi
    fi
fi

log_info ""

# Configure WETH10 Bridge
if [ -n "$WETH10_CHECK" ] && ! echo "$WETH10_CHECK" | grep -qE "^0x0+$" && ! echo "$WETH10_CHECK" | grep -qE "^0x0000000000000000000000000000000000000000$"; then
    log_success "✓ WETH10 bridge already configured for Ethereum Mainnet"
    log_detail "Current destination: $WETH10_CHECK"
else
    log_info "Configuring WETH10 bridge for Ethereum Mainnet..."
    log_info "Waiting for any pending transactions to clear..."
    sleep 15
    
    # Get current gas price and use 10x to ensure replacement
    CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    REPLACEMENT_GAS=$(echo "$CURRENT_GAS * 10" | bc 2>/dev/null || echo "100000000000")
    
    # Try with very high gas price to replace any pending transactions
    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 "$REPLACEMENT_GAS" \
        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 "✓ WETH10 bridge configured: $HASH"
        sleep 5
    else
        ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted|already exists" | head -1 || echo "Unknown")
        if echo "$ERR" | grep -q "already exists"; then
            log_success "✓ WETH10 bridge already configured for Ethereum Mainnet"
        else
            log_error "✗ WETH10 configuration failed: $ERR"
            log_info "Full output: $TX_OUTPUT"
        fi
    fi
fi

log_info ""
log_success "========================================="
log_success "Ethereum Mainnet Configuration Complete!"
log_success "========================================="
log_info ""

