#!/usr/bin/env bash
# Configure all bridge destinations for WETH9 and WETH10
# Usage: ./configure-all-bridge-destinations.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/address-inventory.sh"
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'
CYAN='\033[0;36m'
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"; }
log_fix() { echo -e "${CYAN}[FIX]${NC} $1"; }

load_explorer_runtime_env

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

# Parse arguments
PRIVATE_KEY_ARG="${1:-}"
WETH9_ETH_MAINNET="${2:-}"
WETH10_ETH_MAINNET="${3:-}"

# Use provided private key or from environment
if [ -n "$PRIVATE_KEY_ARG" ]; then
    PRIVATE_KEY="$PRIVATE_KEY_ARG"
elif [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not provided. Usage: $0 [private_key] [weth9_eth_mainnet] [weth10_eth_mainnet]"
    log_info "Or export PRIVATE_KEY before running"
    exit 1
fi

declare -A WETH9_DESTINATIONS=()
declare -A WETH10_DESTINATIONS=()
declare -A CHAIN_NAMES=()

while IFS=$'\t' read -r chain_name selector weth9_dest weth10_dest _rpc_url; do
    CHAIN_NAMES["$selector"]="$chain_name"
    WETH9_DESTINATIONS["$selector"]="$weth9_dest"
    WETH10_DESTINATIONS["$selector"]="$weth10_dest"
done < <(ccip_destination_rows)

# Preserve the manual flow: Ethereum stays TBD unless explicitly provided.
ETHEREUM_MAINNET_SELECTOR="${ETHEREUM_MAINNET_SELECTOR:-$(ccip_destination_selector_by_name "Ethereum Mainnet")}"
WETH9_DESTINATIONS["$ETHEREUM_MAINNET_SELECTOR"]="TBD"
WETH10_DESTINATIONS["$ETHEREUM_MAINNET_SELECTOR"]="TBD"

if [ -n "$WETH9_ETH_MAINNET" ] && echo "$WETH9_ETH_MAINNET" | grep -qE "^0x[0-9a-fA-F]{40}$"; then
    WETH9_DESTINATIONS["$ETHEREUM_MAINNET_SELECTOR"]="$WETH9_ETH_MAINNET"
    log_info "Using provided WETH9 Ethereum Mainnet address: $WETH9_ETH_MAINNET"
fi

if [ -n "$WETH10_ETH_MAINNET" ] && echo "$WETH10_ETH_MAINNET" | grep -qE "^0x[0-9a-fA-F]{40}$"; then
    WETH10_DESTINATIONS["$ETHEREUM_MAINNET_SELECTOR"]="$WETH10_ETH_MAINNET"
    log_info "Using provided WETH10 Ethereum Mainnet address: $WETH10_ETH_MAINNET"
fi

# Get deployer address
DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$DEPLOYER" ]; then
    log_error "Failed to get address from private key"
    exit 1
fi

log_info "========================================="
log_info "Configure All Bridge Destinations"
log_info "========================================="
log_info ""
log_info "Deployer: $DEPLOYER"
log_info "WETH9 Bridge: $WETH9_BRIDGE"
log_info "WETH10 Bridge: $WETH10_BRIDGE"
log_info ""

# Function to configure destination
configure_destination() {
    local bridge="$1"
    local selector="$2"
    local dest_address="$3"
    local chain_name="$4"
    local token_name="$5"
    
    # Check if already configured
    local current=$(cast call "$bridge" "destinations(uint64)" "$selector" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    local current_clean=$(echo "$current" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    
    # Check if result is valid address (not zero or empty)
    if [ -n "$current_clean" ] && ! echo "$current_clean" | grep -qE "^0x0+$" && [ "$current_clean" != "0x0000000000000000000000000000000000000000" ]; then
        log_success "✓ $token_name $chain_name: Already configured ($current_clean)"
        return 0
    fi
    
    if [ "$dest_address" = "TBD" ]; then
        log_warn "⚠ $token_name $chain_name: Address not provided (TBD)"
        return 1
    fi
    
    log_info "Configuring $token_name $chain_name..."
    local nonce=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    local tx_output=$(cast send "$bridge" \
        "addDestination(uint64,address)" \
        "$selector" \
        "$dest_address" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 5000000000 \
        --nonce "$nonce" \
        2>&1 || echo "FAILED")
    
    if echo "$tx_output" | grep -qE "transactionHash"; then
        local tx_hash=$(echo "$tx_output" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ $token_name $chain_name: Configured ($tx_hash)"
        sleep 10
        return 0
    else
        log_error "✗ $token_name $chain_name: Failed"
        log_info "  Output: $(echo "$tx_output" | head -3)"
        return 1
    fi
}

# Configure WETH9 destinations
log_fix "========================================="
log_fix "Configuring WETH9 Bridge Destinations"
log_fix "========================================="
log_info ""

WETH9_SUCCESS=0
WETH9_FAILED=0
WETH9_SKIPPED=0

for SELECTOR in "${!WETH9_DESTINATIONS[@]}"; do
    DEST_ADDRESS="${WETH9_DESTINATIONS[$SELECTOR]}"
    CHAIN_NAME="${CHAIN_NAMES[$SELECTOR]}"
    
    if configure_destination "$WETH9_BRIDGE" "$SELECTOR" "$DEST_ADDRESS" "$CHAIN_NAME" "WETH9"; then
        ((WETH9_SUCCESS++)) || true
    elif [ "$DEST_ADDRESS" = "TBD" ]; then
        ((WETH9_SKIPPED++)) || true
    else
        ((WETH9_FAILED++)) || true
    fi
done

log_info ""
log_info "WETH9 Results: $WETH9_SUCCESS configured, $WETH9_FAILED failed, $WETH9_SKIPPED skipped"
log_info ""

# Configure WETH10 destinations
log_fix "========================================="
log_fix "Configuring WETH10 Bridge Destinations"
log_fix "========================================="
log_info ""

WETH10_SUCCESS=0
WETH10_FAILED=0
WETH10_SKIPPED=0

for SELECTOR in "${!WETH10_DESTINATIONS[@]}"; do
    DEST_ADDRESS="${WETH10_DESTINATIONS[$SELECTOR]}"
    CHAIN_NAME="${CHAIN_NAMES[$SELECTOR]}"
    
    if configure_destination "$WETH10_BRIDGE" "$SELECTOR" "$DEST_ADDRESS" "$CHAIN_NAME" "WETH10"; then
        ((WETH10_SUCCESS++)) || true
    elif [ "$DEST_ADDRESS" = "TBD" ]; then
        ((WETH10_SKIPPED++)) || true
    else
        ((WETH10_FAILED++)) || true
    fi
done

log_info ""
log_info "WETH10 Results: $WETH10_SUCCESS configured, $WETH10_FAILED failed, $WETH10_SKIPPED skipped"
log_info ""

# Final summary
log_info "========================================="
log_info "Configuration Summary"
log_info "========================================="
log_info ""

log_info "WETH9 Bridge:"
log_info "  Configured: $WETH9_SUCCESS"
log_info "  Failed: $WETH9_FAILED"
log_info "  Skipped: $WETH9_SKIPPED (Ethereum Mainnet - address needed)"

log_info ""
log_info "WETH10 Bridge:"
log_info "  Configured: $WETH10_SUCCESS"
log_info "  Failed: $WETH10_FAILED"
log_info "  Skipped: $WETH10_SKIPPED (Ethereum Mainnet - address needed)"

log_info ""

if [ $WETH9_SKIPPED -gt 0 ] || [ $WETH10_SKIPPED -gt 0 ]; then
    log_warn "⚠ Ethereum Mainnet addresses not provided"
    log_info "  To configure Ethereum Mainnet, use:"
    log_info "    ./scripts/fix-bridge-errors.sh [private_key] [ethereum_mainnet_bridge_address]"
fi

if [ $WETH9_FAILED -eq 0 ] && [ $WETH10_FAILED -eq 0 ]; then
    log_success "✓ All provided destinations configured successfully!"
else
    log_warn "⚠ Some destinations failed to configure"
    log_info "  Check transaction outputs above for details"
fi

log_info ""
