#!/usr/bin/env bash
# Configure Ethereum Mainnet Destination
# Tasks 3, 50, 51: Configure Ethereum Mainnet for both bridges
# Usage: ./configure-ethereum-mainnet-destination.sh [private_key]

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"

# 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 .env exists
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
elif [ -f "$PROJECT_ROOT/../.env" ]; then
    source "$PROJECT_ROOT/../.env"
fi

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

if [ -z "$PRIVATE_KEY" ]; then
    log_error "Private key required"
    log_info "Usage: $0 [private_key]"
    log_info "   OR: Set PRIVATE_KEY in .env"
    exit 1
fi

# 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="0xcacfd227A040002e49e2e01626363071324f820a"
WETH10_BRIDGE="0xe0E93247376aa097dB308B92e6Ba36bA015535D0"

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 "RPC URL: $RPC_URL"
log_info ""

# Get current 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 ""

# Check if already configured
log_info "Checking current configuration..."

# destinations() returns a tuple: (uint64, address, bool)
DEST_WETH9=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
DEST_WETH9_HEX=$(echo "$DEST_WETH9" | sed 's/0x//')
DEST_WETH9_CLEAN=""
if [ ${#DEST_WETH9_HEX} -ge 128 ]; then
    ADDR_HEX=$(echo "$DEST_WETH9_HEX" | cut -c65-128)
    DEST_WETH9_CLEAN="0x${ADDR_HEX:24:40}"
fi

if [ -n "$DEST_WETH9_CLEAN" ] && ! echo "$DEST_WETH9_CLEAN" | grep -qE "^0x0+$"; then
    if [ "$(echo "$DEST_WETH9_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$WETH9_MAINNET_BRIDGE" | tr '[:upper:]' '[:lower:]')" ]; then
        log_success "WETH9 Bridge: Already configured correctly"
        WETH9_CONFIGURED=true
    else
        log_warn "WETH9 Bridge: Configured with different address: $DEST_WETH9_CLEAN"
        WETH9_CONFIGURED=false
    fi
else
    log_warn "WETH9 Bridge: Not configured"
    WETH9_CONFIGURED=false
fi

DEST_WETH10=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
DEST_WETH10_HEX=$(echo "$DEST_WETH10" | sed 's/0x//')
DEST_WETH10_CLEAN=""
if [ ${#DEST_WETH10_HEX} -ge 128 ]; then
    ADDR_HEX=$(echo "$DEST_WETH10_HEX" | cut -c65-128)
    DEST_WETH10_CLEAN="0x${ADDR_HEX:24:40}"
fi

if [ -n "$DEST_WETH10_CLEAN" ] && ! echo "$DEST_WETH10_CLEAN" | grep -qE "^0x0+$"; then
    if [ "$(echo "$DEST_WETH10_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$WETH10_MAINNET_BRIDGE" | tr '[:upper:]' '[:lower:]')" ]; then
        log_success "WETH10 Bridge: Already configured correctly"
        WETH10_CONFIGURED=true
    else
        log_warn "WETH10 Bridge: Configured with different address: $DEST_WETH10_CLEAN"
        WETH10_CONFIGURED=false
    fi
else
    log_warn "WETH10 Bridge: Not configured"
    WETH10_CONFIGURED=false
fi

log_info ""

# Configure WETH9 Bridge
if [ "$WETH9_CONFIGURED" = "false" ]; then
    log_info "Configuring WETH9 Bridge..."
    log_info "  Calling: addDestination($ETHEREUM_MAINNET_SELECTOR, $WETH9_MAINNET_BRIDGE)"
    
    # Get optimal gas price (use Etherscan API if available, otherwise use high multiplier)
    if [ -f "$SCRIPT_DIR/get-optimal-gas-from-api.sh" ]; then
        BASE_GAS=$("$SCRIPT_DIR/get-optimal-gas-from-api.sh" "fast" 2>/dev/null || echo "")
        if [ -n "$BASE_GAS" ] && [ "$BASE_GAS" != "0" ]; then
            # Use 2x fast gas for replacement transaction
            GAS_PRICE=$(echo "scale=0; $BASE_GAS * 2 / 1" | bc 2>/dev/null || echo "10000000000")
        else
            GAS_PRICE=10000000000  # 10 gwei fallback
        fi
    else
        CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
        GAS_PRICE=$(echo "scale=0; $CURRENT_GAS * 10 / 1" | bc 2>/dev/null || echo "10000000000")
    fi
    
    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" \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -q "0x[0-9a-fA-F]\{64\}"; then
        TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "0x[0-9a-fA-F]{64}" | head -1)
        log_success "WETH9 Bridge: Transaction sent: $TX_HASH"
        ((CURRENT_NONCE++)) || true
    else
        log_error "WETH9 Bridge: Transaction failed"
        log_error "$TX_OUTPUT"
    fi
else
    log_info "Skipping WETH9 Bridge (already configured)"
fi

# Configure WETH10 Bridge
if [ "$WETH10_CONFIGURED" = "false" ]; then
    log_info ""
    log_info "Configuring WETH10 Bridge..."
    log_info "  Calling: addDestination($ETHEREUM_MAINNET_SELECTOR, $WETH10_MAINNET_BRIDGE)"
    
    # Get optimal gas price (use Etherscan API if available, otherwise use high multiplier)
    if [ -f "$SCRIPT_DIR/get-optimal-gas-from-api.sh" ]; then
        BASE_GAS=$("$SCRIPT_DIR/get-optimal-gas-from-api.sh" "fast" 2>/dev/null || echo "")
        if [ -n "$BASE_GAS" ] && [ "$BASE_GAS" != "0" ]; then
            # Use 2x fast gas for replacement transaction
            GAS_PRICE=$(echo "scale=0; $BASE_GAS * 2 / 1" | bc 2>/dev/null || echo "10000000000")
        else
            GAS_PRICE=10000000000  # 10 gwei fallback
        fi
    else
        CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
        GAS_PRICE=$(echo "scale=0; $CURRENT_GAS * 10 / 1" | bc 2>/dev/null || echo "10000000000")
    fi
    
    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" \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -q "0x[0-9a-fA-F]\{64\}"; then
        TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "0x[0-9a-fA-F]{64}" | head -1)
        log_success "WETH10 Bridge: Transaction sent: $TX_HASH"
    else
        log_error "WETH10 Bridge: Transaction failed"
        log_error "$TX_OUTPUT"
    fi
else
    log_info "Skipping WETH10 Bridge (already configured)"
fi

# Verify configuration
log_info ""
log_info "========================================="
log_info "Verifying Configuration"
log_info "========================================="
log_info ""

sleep 2  # Wait for transaction to be mined

# Extract address from tuple
DEST_WETH9=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
DEST_WETH9_HEX=$(echo "$DEST_WETH9" | sed 's/0x//')
DEST_WETH9_CLEAN=""
if [ ${#DEST_WETH9_HEX} -ge 128 ]; then
    ADDR_HEX=$(echo "$DEST_WETH9_HEX" | cut -c65-128)
    DEST_WETH9_CLEAN="0x${ADDR_HEX:24:40}"
fi

if [ -n "$DEST_WETH9_CLEAN" ] && ! echo "$DEST_WETH9_CLEAN" | grep -qE "^0x0+$"; then
    log_success "WETH9 Bridge: Configured - $DEST_WETH9_CLEAN"
else
    log_warn "WETH9 Bridge: Still not configured (transaction may be pending)"
fi

DEST_WETH10=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
DEST_WETH10_HEX=$(echo "$DEST_WETH10" | sed 's/0x//')
DEST_WETH10_CLEAN=""
if [ ${#DEST_WETH10_HEX} -ge 128 ]; then
    ADDR_HEX=$(echo "$DEST_WETH10_HEX" | cut -c65-128)
    DEST_WETH10_CLEAN="0x${ADDR_HEX:24:40}"
fi

if [ -n "$DEST_WETH10_CLEAN" ] && ! echo "$DEST_WETH10_CLEAN" | grep -qE "^0x0+$"; then
    log_success "WETH10 Bridge: Configured - $DEST_WETH10_CLEAN"
else
    log_warn "WETH10 Bridge: Still not configured (transaction may be pending)"
fi

log_info ""
log_info "========================================="
log_info "Configuration Complete"
log_info "========================================="
log_info ""
log_info "To verify all destinations:"
log_info "  ./scripts/check-bridge-config.sh"
log_info ""
