#!/usr/bin/env bash
# Configure Ethereum Mainnet using new deployer account
# This bypasses the stuck transaction on the old account
# Usage: ./configure-ethereum-mainnet-with-new-account.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"

# New deployer account
NEW_DEPLOYER="0xC13EfAe66708C7541d2D66A2527bcBF9992e7186"

# Check if NEW_PRIVATE_KEY is set, otherwise prompt
if [ -z "${NEW_PRIVATE_KEY:-}" ]; then
    log_warn "⚠ NEW_PRIVATE_KEY not set in .env"
    log_info "Please set NEW_PRIVATE_KEY in $SOURCE_PROJECT/.env"
    log_info "Or export it: export NEW_PRIVATE_KEY=<private-key>"
    exit 1
fi

# Verify new deployer address matches
VERIFIED_DEPLOYER=$(cast wallet address --private-key "$NEW_PRIVATE_KEY" 2>/dev/null || echo "")
if [ "$VERIFIED_DEPLOYER" != "$NEW_DEPLOYER" ]; then
    log_error "NEW_PRIVATE_KEY does not match expected address"
    log_info "Expected: $NEW_DEPLOYER"
    log_info "Got: $VERIFIED_DEPLOYER"
    exit 1
fi

log_info "========================================="
log_info "Configure Ethereum Mainnet (New Account)"
log_info "========================================="
log_info ""
log_info "New Deployer: $NEW_DEPLOYER"
log_info "WETH9 Bridge: $WETH9_BRIDGE"
log_info "WETH10 Bridge: $WETH10_BRIDGE"
log_info "Ethereum Mainnet Selector: $ETHEREUM_MAINNET_SELECTOR"
log_info ""

# Check balance
BALANCE=$(cast balance "$NEW_DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
BALANCE_ETH=$(echo "scale=4; $BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "New deployer balance: $BALANCE_ETH ETH"

if (( $(echo "$BALANCE_ETH < 1" | bc -l 2>/dev/null || echo "1") )); then
    log_error "Insufficient balance. Need at least 1 ETH for gas"
    log_info "Run: ./scripts/fund-new-deployer-account.sh"
    exit 1
fi

# Get optimal gas price
CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
OPTIMAL_GAS=$(echo "$CURRENT_GAS * 2" | bc 2>/dev/null || echo "2000000000")
log_info "Using gas price: $(echo "scale=2; $OPTIMAL_GAS / 1000000000" | bc) gwei"
log_info ""

# Configure WETH9 Bridge
log_info "Configuring WETH9 bridge for Ethereum Mainnet..."
TX_OUTPUT=$(cast send "$WETH9_BRIDGE" \
    "addDestination(uint64,address)" \
    "$ETHEREUM_MAINNET_SELECTOR" \
    "$WETH9_MAINNET_BRIDGE" \
    --rpc-url "$RPC_URL" \
    --private-key "$NEW_PRIVATE_KEY" \
    --gas-price "$OPTIMAL_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 "✓ WETH9 bridge configured: $HASH"
    sleep 10
else
    ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted" | head -1 || echo "Unknown")
    log_error "✗ WETH9 configuration failed: $ERR"
    if echo "$ERR" | grep -q "underpriced"; then
        log_warn "⚠ Still blocked - may need higher gas price"
    fi
fi

log_info ""

# Configure WETH10 Bridge
log_info "Configuring WETH10 bridge for Ethereum Mainnet..."
TX_OUTPUT=$(cast send "$WETH10_BRIDGE" \
    "addDestination(uint64,address)" \
    "$ETHEREUM_MAINNET_SELECTOR" \
    "$WETH10_MAINNET_BRIDGE" \
    --rpc-url "$RPC_URL" \
    --private-key "$NEW_PRIVATE_KEY" \
    --gas-price "$OPTIMAL_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 "✓ WETH10 bridge configured: $HASH"
    sleep 10
else
    ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted" | head -1 || echo "Unknown")
    log_error "✗ WETH10 configuration failed: $ERR"
    if echo "$ERR" | grep -q "underpriced"; then
        log_warn "⚠ Still blocked - may need higher gas price"
    fi
fi

log_info ""

# Verify configuration
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 "")

log_info ""
log_success "========================================="
log_success "Verification Results"
log_success "========================================="
log_info ""

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

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

log_info ""

if [ "$WETH9_OK" = true ] && [ "$WETH10_OK" = true ]; then
    log_success "✅ Ethereum Mainnet configuration complete!"
    log_info ""
    log_info "Run test to verify:"
    log_info "  ./scripts/test-bridge-all-7-networks.sh weth9"
    log_info ""
    log_info "Note: You may need to update PRIVATE_KEY in .env to use new account for future operations"
else
    log_warn "⚠ Configuration incomplete"
    log_info ""
    log_info "If still failing, check:"
    log_info "  1. New account has sufficient balance"
    log_info "  2. Gas price is appropriate"
    log_info "  3. Bridge contracts are accessible"
fi

log_info ""

