#!/usr/bin/env bash
# Bridge 1 ETH to each of the 6 destination chains
# Usage: ./bridge-eth-to-all-chains.sh [token] [amount]
# Example: ./bridge-eth-to-all-chains.sh weth9 1.0

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && 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

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-0xe0E93247376aa097dB308B92e6Ba36bA015535D0}"

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

# Destination chains (7 total including Ethereum Mainnet)
declare -A CHAIN_SELECTORS=(
    ["BSC"]="11344663589394136015"
    ["Polygon"]="4051577828743386545"
    ["Avalanche"]="6433500567565415381"
    ["Base"]="15971525489660198786"
    ["Arbitrum"]="4949039107694359620"
    ["Optimism"]="3734403246176062136"
    ["Ethereum"]="5009297550715157269"
)

# Determine token and bridge
if [ "$TOKEN" = "weth9" ]; then
    TOKEN_ADDRESS="$WETH9_ADDRESS"
    BRIDGE_ADDRESS="$WETH9_BRIDGE"
    TOKEN_NAME="WETH9"
elif [ "$TOKEN" = "weth10" ]; then
    TOKEN_ADDRESS="$WETH10_ADDRESS"
    BRIDGE_ADDRESS="$WETH10_BRIDGE"
    TOKEN_NAME="WETH10"
else
    log_error "Invalid token: $TOKEN (use weth9 or weth10)"
    exit 1
fi

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 "Bridge ETH to All Chains"
log_info "========================================="
log_info ""
log_info "Configuration:"
log_info "  Token: $TOKEN_NAME"
log_info "  Amount per chain: $AMOUNT ETH"
log_info "  Total amount: $(echo "scale=2; $AMOUNT * 6" | bc) ETH"
log_info "  Deployer: $DEPLOYER"
log_info "  Bridge: $BRIDGE_ADDRESS"
log_info ""

# Check ETH balance
log_info "Checking ETH balance..."
ETH_BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ETH_BALANCE_ETH=$(echo "scale=6; $ETH_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
REQUIRED_ETH=$(echo "scale=2; $AMOUNT * 6" | bc)

log_info "ETH Balance: $ETH_BALANCE_ETH ETH"
log_info "Required: $REQUIRED_ETH ETH (plus gas fees)"

if (( $(echo "$ETH_BALANCE_ETH < $REQUIRED_ETH" | bc -l 2>/dev/null || echo 1) )); then
    log_error "Insufficient ETH balance. Need at least $REQUIRED_ETH ETH"
    exit 1
fi

log_success "✓ Sufficient balance"
log_info ""

# Convert amount to wei
AMOUNT_WEI=$(cast --to-wei "$AMOUNT" ether 2>/dev/null || echo "")
if [ -z "$AMOUNT_WEI" ]; then
    log_error "Failed to convert amount to wei"
    exit 1
fi

TOTAL_AMOUNT_WEI=$(echo "$AMOUNT_WEI * 6" | bc)

# Step 1: Wrap total ETH needed
log_info "Step 1: Wrapping $(echo "scale=2; $AMOUNT * 6" | bc) ETH to $TOKEN_NAME..."
WRAP_TX=$(cast send "$TOKEN_ADDRESS" "deposit()" --value "$TOTAL_AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --gas-price 1000000000 2>&1 || echo "")

if echo "$WRAP_TX" | grep -qE "(blockHash|transactionHash)"; then
    TX_HASH=$(echo "$WRAP_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
    log_success "✓ ETH wrapped to $TOKEN_NAME"
    if [ -n "$TX_HASH" ]; then
        log_info "Transaction: $TX_HASH"
    fi
    sleep 3  # Wait for transaction to be mined
else
    log_error "Failed to wrap ETH"
    log_info "Output: $WRAP_TX"
    exit 1
fi

log_info ""

# Step 2: Approve bridge for total amount
log_info "Step 2: Approving bridge to spend $TOKEN_NAME..."
APPROVE_TX=$(cast send "$TOKEN_ADDRESS" "approve(address,uint256)" "$BRIDGE_ADDRESS" "$TOTAL_AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --gas-price 1000000000 2>&1 || echo "")

if echo "$APPROVE_TX" | grep -qE "(blockHash|transactionHash)"; then
    TX_HASH=$(echo "$APPROVE_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
    log_success "✓ Bridge approved"
    if [ -n "$TX_HASH" ]; then
        log_info "Transaction: $TX_HASH"
    fi
    sleep 3
else
    log_error "Failed to approve bridge"
    log_info "Output: $APPROVE_TX"
    exit 1
fi

log_info ""

# Step 3: Send to each chain
log_info "Step 3: Sending $AMOUNT ETH to each destination chain..."
log_info ""

TRANSFER_COUNT=0
declare -a TRANSACTION_HASHES=()

for chain in "${!CHAIN_SELECTORS[@]}"; do
    selector="${CHAIN_SELECTORS[$chain]}"
    
    log_info "Sending to $chain (Selector: $selector)..."
    
    # Calculate fee first
    FEE=$(cast call "$BRIDGE_ADDRESS" "calculateFee(uint64,uint256)" "$selector" "$AMOUNT_WEI" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$FEE" != "0" ] && [ -n "$FEE" ]; then
        FEE_ETH=$(echo "scale=10; $FEE / 1000000000000000000" | bc 2>/dev/null || echo "0")
        log_info "  Fee: $FEE_ETH ETH"
    fi
    
    # Send transfer
    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 "✓ Transfer to $chain initiated"
            log_info "  Transaction: $TX_HASH"
            TRANSACTION_HASHES+=("$chain:$TX_HASH")
            ((TRANSFER_COUNT++))
            sleep 2  # Wait between transfers
        else
            log_warn "⚠ Transfer to $chain initiated but hash not extracted"
        fi
    else
        log_error "✗ Failed to send to $chain"
        log_info "Output: $SEND_TX"
    fi
    
    log_info ""
done

# Summary
log_success "========================================="
log_success "Bridge Transfers Complete!"
log_success "========================================="
log_info ""
log_info "Summary:"
log_info "  Token: $TOKEN_NAME"
log_info "  Amount per chain: $AMOUNT ETH"
log_info "  Successful transfers: $TRANSFER_COUNT/6"
log_info ""
log_info "Transaction Hashes:"
for entry in "${TRANSACTION_HASHES[@]}"; do
    chain=$(echo "$entry" | cut -d: -f1)
    hash=$(echo "$entry" | cut -d: -f2-)
    log_info "  $chain: $hash"
done
log_info ""
log_info "Next Steps:"
log_info "  1. Monitor transfers on source chain"
log_info "  2. Wait for CCIP processing (1-5 minutes)"
log_info "  3. Verify receipts on destination chains"
log_info ""

