#!/usr/bin/env bash
# Complete bridge process with proper error handling and LINK token support
# Usage: ./bridge-eth-complete.sh [amount_per_chain]

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}"
LINK_TOKEN="0x514910771af9ca656af840dff83e8264ecf986ca"

AMOUNT="${1:-1.0}"
AMOUNT_WEI=$(cast --to-wei "$AMOUNT" ether 2>/dev/null)
TOTAL_AMOUNT_WEI=$(echo "$AMOUNT_WEI * 6" | bc)

DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)

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

log_info "========================================="
log_info "Complete Bridge Process"
log_info "========================================="
log_info ""
log_info "Amount per chain: $AMOUNT ETH"
log_info "Total needed: $(echo "scale=2; $AMOUNT * 6" | bc) ETH"
log_info "Deployer: $DEPLOYER"
log_info ""

# Check current status
log_info "Checking current status..."
WETH9_BAL=$(cast call "$WETH9_ADDRESS" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ALLOW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
LINK_BAL=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

log_info "WETH9 Balance: $WETH9_BAL wei"
log_info "Bridge Allowance: $ALLOW wei"
log_info "LINK Balance: $LINK_BAL wei"
log_info ""

# Step 1: Wrap ETH if needed
if [ "$WETH9_BAL" = "0" ] || (( $(echo "$WETH9_BAL < $TOTAL_AMOUNT_WEI" | bc -l 2>/dev/null || echo 1) )); then
    log_info "Step 1: Wrapping ETH to WETH9..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WRAP_TX=$(cast send "$WETH9_ADDRESS" "deposit()" \
        --value "$TOTAL_AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 5000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "")
    
    if echo "$WRAP_TX" | grep -qE "transactionHash"; then
        TX_HASH=$(echo "$WRAP_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ Wrap transaction: $TX_HASH"
        log_info "Waiting for confirmation..."
        sleep 15
    else
        log_error "Failed to wrap ETH"
        log_info "$WRAP_TX"
        exit 1
    fi
else
    log_success "✓ WETH9 balance sufficient"
fi

# Step 2: Approve bridge if needed
ALLOW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
if [ "$ALLOW" = "0" ] || (( $(echo "$ALLOW < $TOTAL_AMOUNT_WEI" | bc -l 2>/dev/null || echo 1) )); then
    log_info "Step 2: Approving bridge..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    APPROVE_TX=$(cast send "$WETH9_ADDRESS" "approve(address,uint256)" \
        "$WETH9_BRIDGE" \
        "$TOTAL_AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 5000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "")
    
    if echo "$APPROVE_TX" | grep -qE "transactionHash"; then
        TX_HASH=$(echo "$APPROVE_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ Approve transaction: $TX_HASH"
        log_info "Waiting for confirmation..."
        sleep 15
    else
        log_error "Failed to approve bridge"
        log_info "$APPROVE_TX"
        exit 1
    fi
else
    log_success "✓ Bridge allowance sufficient"
fi

# Step 3: Check LINK balance and estimate fees
log_info "Step 3: Checking LINK token requirements..."
ESTIMATED_FEE_TOTAL=0
for chain in "${!CHAIN_SELECTORS[@]}"; do
    selector="${CHAIN_SELECTORS[$chain]}"
    FEE=$(cast call "$WETH9_BRIDGE" "calculateFee(uint64,uint256)" "$selector" "$AMOUNT_WEI" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$FEE" != "0" ]; then
        ESTIMATED_FEE_TOTAL=$(echo "$ESTIMATED_FEE_TOTAL + $FEE" | bc)
    fi
done

LINK_BAL=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
LINK_NEEDED_ETH=$(echo "scale=6; $ESTIMATED_FEE_TOTAL / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info "Estimated total fees: $LINK_NEEDED_ETH LINK"
log_info "Current LINK balance: $(echo "scale=6; $LINK_BAL / 1000000000000000000" | bc) LINK"

if (( $(echo "$LINK_BAL < $ESTIMATED_FEE_TOTAL" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "⚠ Insufficient LINK tokens for fees"
    log_info "Need approximately $LINK_NEEDED_ETH LINK tokens"
    log_info "You may need to:"
    log_info "  1. Transfer LINK tokens to this address"
    log_info "  2. Or deploy/mint LINK tokens if this is a test network"
    log_info ""
    log_warn "Continuing anyway - transfers will fail if fees are insufficient"
fi

log_info ""

# Step 4: Send to all chains
log_info "Step 4: Sending to all destination 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..."
    
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    SEND_TX=$(cast send "$WETH9_BRIDGE" \
        "sendCrossChain(uint64,address,uint256)" \
        "$selector" \
        "$DEPLOYER" \
        "$AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 5000000000 \
        --nonce "$CURRENT_NONCE" \
        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}')
        log_success "✓ $chain: $TX_HASH"
        TRANSACTION_HASHES+=("$chain:$TX_HASH")
        ((TRANSFER_COUNT++))
        sleep 5  # Wait between transfers
    else
        ERROR_MSG=$(echo "$SEND_TX" | grep -E "Error|reverted" | head -1 || echo "Unknown error")
        log_error "✗ $chain: $ERROR_MSG"
    fi
done

log_info ""
log_success "========================================="
log_success "Bridge Process Complete!"
log_success "========================================="
log_info ""
log_info "Summary:"
log_info "  Successful transfers: $TRANSFER_COUNT/6"
log_info ""
if [ ${#TRANSACTION_HASHES[@]} -gt 0 ]; then
    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
fi
log_info ""

