#!/usr/bin/env bash
# Continue bridging ETH to all chains (skip wrap/approve if already done)
# Usage: ./bridge-eth-to-all-chains-continue.sh [token] [amount]

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"; }

source "$SOURCE_PROJECT/.env"

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"

TOKEN="${1:-weth9}"
AMOUNT="${2:-1.0}"

declare -A CHAIN_SELECTORS=(
    ["BSC"]="11344663589394136015"
    ["Polygon"]="4051577828743386545"
    ["Avalanche"]="6433500567565415381"
    ["Base"]="15971525489660198786"
    ["Arbitrum"]="4949039107694359620"
    ["Optimism"]="3734403246176062136"
)

TOKEN_ADDRESS="$WETH9_ADDRESS"
BRIDGE_ADDRESS="$WETH9_BRIDGE"
TOKEN_NAME="WETH9"

DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)
AMOUNT_WEI=$(cast --to-wei "$AMOUNT" ether 2>/dev/null)

log_info "========================================="
log_info "Bridge ETH to All Chains (Continue)"
log_info "========================================="
log_info ""
log_info "Sending $AMOUNT ETH to each of 6 chains..."
log_info ""

TRANSFER_COUNT=0
declare -a TRANSACTION_HASHES=()

for chain in "${!CHAIN_SELECTORS[@]}"; do
    selector="${CHAIN_SELECTORS[$chain]}"
    
    log_info "Sending to $chain..."
    
    SEND_TX=$(cast send "$BRIDGE_ADDRESS" "sendCrossChain(uint64,address,uint256)" "$selector" "$DEPLOYER" "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --gas-price 1000000000 2>&1 || echo "")
    
    if echo "$SEND_TX" | grep -qE "transactionHash"; then
        TX_HASH=$(echo "$SEND_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
        if [ -n "$TX_HASH" ]; then
            log_success "✓ $chain: $TX_HASH"
            TRANSACTION_HASHES+=("$chain:$TX_HASH")
            ((TRANSFER_COUNT++))
            sleep 2
        fi
    elif echo "$SEND_TX" | grep -q "Known transaction"; then
        log_warn "⚠ $chain: Transaction already submitted"
    else
        log_error "✗ $chain: Failed"
        log_info "  $SEND_TX"
    fi
done

log_info ""
log_success "========================================="
log_success "Complete: $TRANSFER_COUNT/6 transfers"
log_success "========================================="
log_info ""
for entry in "${TRANSACTION_HASHES[@]}"; do
    chain=$(echo "$entry" | cut -d: -f1)
    hash=$(echo "$entry" | cut -d: -f2-)
    log_info "$chain: $hash"
done

