#!/usr/bin/env bash
# Test bridge transfers to destination chains
# Usage: ./test-bridge-transfers.sh [chain] [amount] [token]
# Example: ./test-bridge-transfers.sh bsc 0.01 weth9

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

# Destination chain configurations
declare -A CHAIN_SELECTORS=(
    ["bsc"]="11344663589394136015"
    ["polygon"]="4051577828743386545"
    ["avalanche"]="6433500567565415381"
    ["base"]="15971525489660198786"
    ["arbitrum"]="4949039107694359620"
    ["optimism"]="3734403246176062136"
)

declare -A CHAIN_NAMES=(
    ["bsc"]="BSC"
    ["polygon"]="Polygon"
    ["avalanche"]="Avalanche"
    ["base"]="Base"
    ["arbitrum"]="Arbitrum"
    ["optimism"]="Optimism"
)

# Parse arguments
CHAIN="${1:-}"
AMOUNT="${2:-0.01}"
TOKEN="${3:-weth9}"

if [ -z "$CHAIN" ]; then
    log_info "Usage: $0 [chain] [amount] [token]"
    log_info "Chains: bsc, polygon, avalanche, base, arbitrum, optimism"
    log_info "Example: $0 bsc 0.01 weth9"
    exit 1
fi

if [ -z "${CHAIN_SELECTORS[$CHAIN]:-}" ]; then
    log_error "Invalid chain: $CHAIN"
    log_info "Valid chains: bsc, polygon, avalanche, base, arbitrum, optimism"
    exit 1
fi

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not set in .env file"
    exit 1
fi

SELECTOR="${CHAIN_SELECTORS[$CHAIN]}"
CHAIN_NAME="${CHAIN_NAMES[$CHAIN]}"

# 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

log_info "========================================="
log_info "Test Bridge Transfer"
log_info "========================================="
log_info ""
log_info "Configuration:"
log_info "  Destination: $CHAIN_NAME (Selector: $SELECTOR)"
log_info "  Token: $TOKEN_NAME"
log_info "  Amount: $AMOUNT ETH"
log_info "  Bridge: $BRIDGE_ADDRESS"
log_info "  RPC: $RPC_URL"
log_info ""

# Get deployer address
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 "Deployer: $DEPLOYER"
log_info ""

# Step 1: Check ETH balance
log_info "Step 1: 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")
log_info "ETH Balance: $ETH_BALANCE_ETH ETH"

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

# Step 2: Wrap ETH to WETH
log_info ""
log_info "Step 2: Wrapping $AMOUNT ETH to $TOKEN_NAME..."
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

if [ "$TOKEN" = "weth9" ]; then
    WRAP_TX=$(cast send "$TOKEN_ADDRESS" "deposit()" --value "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" 2>&1 || echo "")
else
    WRAP_TX=$(cast send "$TOKEN_ADDRESS" "deposit()" --value "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" 2>&1 || echo "")
fi

if echo "$WRAP_TX" | grep -qE "(blockHash|transactionHash)"; then
    log_success "✓ ETH wrapped to $TOKEN_NAME"
    sleep 2  # Wait for transaction to be mined
else
    log_error "Failed to wrap ETH"
    log_info "Output: $WRAP_TX"
    exit 1
fi

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

if echo "$APPROVE_TX" | grep -qE "(blockHash|transactionHash)"; then
    log_success "✓ Bridge approved"
    sleep 2
else
    log_error "Failed to approve bridge"
    log_info "Output: $APPROVE_TX"
    exit 1
fi

# Step 4: Calculate fee
log_info ""
log_info "Step 4: Calculating CCIP fee..."
FEE=$(cast call "$BRIDGE_ADDRESS" "calculateFee(uint64,uint256)" "$SELECTOR" "$AMOUNT_WEI" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
FEE_ETH=$(echo "scale=10; $FEE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "Fee: $FEE_ETH ETH ($FEE wei)"

# Step 5: Send cross-chain transfer
log_info ""
log_info "Step 5: Sending cross-chain transfer to $CHAIN_NAME..."
log_info "  Recipient: $DEPLOYER (same address on destination)"
log_info "  Amount: $AMOUNT $TOKEN_NAME"

SEND_TX=$(cast send "$BRIDGE_ADDRESS" "sendCrossChain(uint64,address,uint256)" "$SELECTOR" "$DEPLOYER" "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" 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 initiated"
        log_info "Transaction Hash: $TX_HASH"
        log_info ""
        log_info "Monitor transfer:"
        log_info "  - Check events on source chain"
        log_info "  - Wait for CCIP processing (1-5 minutes)"
        log_info "  - Check destination chain for receipt"
    else
        log_warn "Transfer initiated but could not extract transaction hash"
        log_info "Output: $SEND_TX"
    fi
else
    log_error "Failed to send cross-chain transfer"
    log_info "Output: $SEND_TX"
    exit 1
fi

log_info ""
log_success "========================================="
log_success "Test Transfer Complete!"
log_success "========================================="
log_info ""
log_info "Summary:"
log_info "  Destination: $CHAIN_NAME"
log_info "  Token: $TOKEN_NAME"
log_info "  Amount: $AMOUNT ETH"
log_info "  Transaction: $TX_HASH"
log_info ""

