#!/usr/bin/env bash
# Bridge 1 ETH to all 7 destination chains (including Ethereum Mainnet)
# Usage: ./bridge-to-all-7-chains.sh [token] [amount]
# Example: ./bridge-to-all-7-chains.sh weth9 1.0

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"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-0xe0E93247376aa097dB308B92e6Ba36bA015535D0}"

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

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

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

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

# Check allowance
log_info "Checking allowance..."
ALLOW=$(cast call "$TOKEN_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ALLOW_ETH=$(echo "scale=6; $ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
REQUIRED_AMOUNT=$(echo "scale=2; $AMOUNT * 7" | bc)

log_info "Current allowance: $ALLOW_ETH ETH"
log_info "Required: $REQUIRED_AMOUNT ETH"

if (( $(echo "$ALLOW_ETH < $REQUIRED_AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "⚠ Insufficient allowance. Need to approve first."
    log_info "Approving bridge..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    APPROVE_AMOUNT=$(cast --to-wei "$REQUIRED_AMOUNT" ether 2>/dev/null)
    
    TX_OUTPUT=$(cast send "$TOKEN_ADDRESS" \
        "approve(address,uint256)" \
        "$BRIDGE_ADDRESS" \
        "$APPROVE_AMOUNT" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 20000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "transactionHash"; then
        HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ Approval sent: $HASH"
        log_info "Waiting 30 seconds for confirmation..."
        sleep 30
    elif echo "$TX_OUTPUT" | grep -q "Known transaction"; then
        log_warn "⚠ Approval already pending. Waiting 30 seconds..."
        sleep 30
    else
        log_error "✗ Approval failed: $(echo "$TX_OUTPUT" | grep -E "Error" | head -1 || echo "Unknown")"
        exit 1
    fi
    
    # Check again
    ALLOW=$(cast call "$TOKEN_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    ALLOW_ETH=$(echo "scale=6; $ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
    
    if (( $(echo "$ALLOW_ETH < $REQUIRED_AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
        log_warn "⚠ Allowance still insufficient. Waiting another 30 seconds..."
        sleep 30
        ALLOW=$(cast call "$TOKEN_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        ALLOW_ETH=$(echo "scale=6; $ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
    fi
fi

if (( $(echo "$ALLOW_ETH < $REQUIRED_AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
    log_error "✗ Insufficient allowance after waiting. Current: $ALLOW_ETH ETH, Required: $REQUIRED_AMOUNT ETH"
    exit 1
fi

log_success "✓ Allowance sufficient: $ALLOW_ETH ETH"
log_info ""

# Send to all chains
log_info "Sending $AMOUNT ETH to each of 7 chains..."
log_info ""

SUCCESS=0
declare -a TX_HASHES=()

for chain in "${!CHAIN_SELECTORS[@]}"; do
    selector="${CHAIN_SELECTORS[$chain]}"
    
    log_info "Sending to $chain (Selector: $selector)..."
    
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    TX_OUTPUT=$(cast send "$BRIDGE_ADDRESS" \
        "sendCrossChain(uint64,address,uint256)" \
        "$selector" \
        "$DEPLOYER" \
        "$AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 20000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "transactionHash"; then
        HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ $chain: $HASH"
        TX_HASHES+=("$chain:$HASH")
        ((SUCCESS++))
        sleep 5  # Wait between transfers
    else
        ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted|insufficient" | head -1 || echo "Unknown error")
        log_error "✗ $chain: $ERR"
    fi
done

log_info ""
log_success "========================================="
log_success "Bridge Transfers Complete!"
log_success "========================================="
log_info ""
log_info "Summary:"
log_info "  Successful: $SUCCESS/7"
log_info ""

if [ ${#TX_HASHES[@]} -gt 0 ]; then
    log_info "Transaction Hashes:"
    for entry in "${TX_HASHES[@]}"; do
        chain=$(echo "$entry" | cut -d: -f1)
        hash=$(echo "$entry" | cut -d: -f2-)
        log_info "  $chain: $hash"
    done
fi

log_info ""
log_info "Next Steps:"
log_info "  1. Monitor transfers on source chain"
log_info "  2. Wait for CCIP processing (1-5 minutes per chain)"
log_info "  3. Verify receipts on destination chains"

