#!/usr/bin/env bash
# DRY-RUN: Simulate bridging ETH to all 7 destination chains (including Ethereum Mainnet)
# Usage: ./bridge-eth-to-all-7-chains-dry-run.sh [token] [amount]
# Example: ./bridge-eth-to-all-7-chains-dry-run.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'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
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"; }
log_dryrun() { echo -e "${CYAN}[DRY-RUN]${NC} $1"; }
log_sim() { echo -e "${MAGENTA}[SIMULATE]${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}"

# 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"
)

# 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_dryrun "========================================="
log_dryrun "DRY-RUN: Bridge ETH to All 7 Chains"
log_dryrun "========================================="
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 * 7" | bc) ETH"
log_info "  Deployer: $DEPLOYER"
log_info "  Bridge: $BRIDGE_ADDRESS"
log_info "  Token Contract: $TOKEN_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 * 7" | bc)
ESTIMATED_GAS=$(echo "scale=2; 0.01 * 7" | bc)  # Rough estimate: 0.01 ETH per transaction
TOTAL_NEEDED=$(echo "scale=2; $REQUIRED_ETH + $ESTIMATED_GAS" | bc)

log_info "ETH Balance: $ETH_BALANCE_ETH ETH"
log_info "Required for tokens: $REQUIRED_ETH ETH"
log_info "Estimated gas fees: ~$ESTIMATED_GAS ETH"
log_info "Total needed: ~$TOTAL_NEEDED ETH"

if (( $(echo "$ETH_BALANCE_ETH < $TOTAL_NEEDED" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "⚠ Insufficient ETH balance for this operation"
    log_warn "   Current: $ETH_BALANCE_ETH ETH"
    log_warn "   Needed: ~$TOTAL_NEEDED ETH"
else
    log_success "✓ Sufficient ETH balance"
fi
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 * 7" | bc)

# Check current token balance
log_info "Checking $TOKEN_NAME balance..."
TOKEN_BALANCE=$(cast call "$TOKEN_ADDRESS" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
TOKEN_BALANCE_ETH=$(echo "scale=6; $TOKEN_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
if [ -z "$TOKEN_BALANCE_ETH" ] || [ "$TOKEN_BALANCE_ETH" = "" ]; then
    TOKEN_BALANCE_ETH="0"
fi
REQUIRED_TOKEN=$(echo "scale=2; $AMOUNT * 7" | bc)

log_info "Current $TOKEN_NAME balance: $TOKEN_BALANCE_ETH ETH"
log_info "Required: $REQUIRED_TOKEN ETH"

if (( $(echo "$TOKEN_BALANCE_ETH < $REQUIRED_TOKEN" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "⚠ Insufficient $TOKEN_NAME balance"
    log_sim "Would need to wrap $(echo "scale=2; $REQUIRED_TOKEN - $TOKEN_BALANCE_ETH" | bc) ETH to $TOKEN_NAME"
    log_sim "Transaction: deposit() with value $(echo "scale=2; $REQUIRED_TOKEN - $TOKEN_BALANCE_ETH" | bc) ETH"
else
    log_success "✓ Sufficient $TOKEN_NAME balance"
fi
log_info ""

# Check allowance
log_info "Checking bridge 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")
if [ -z "$ALLOW_ETH" ] || [ "$ALLOW_ETH" = "" ]; then
    ALLOW_ETH="0"
fi

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

if (( $(echo "$ALLOW_ETH < $REQUIRED_TOKEN" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "⚠ Insufficient allowance"
    log_sim "Would need to approve bridge"
    log_sim "Transaction: approve($BRIDGE_ADDRESS, $REQUIRED_TOKEN ETH)"
    log_sim "Function: approve(address,uint256)"
    log_sim "  - spender: $BRIDGE_ADDRESS"
    log_sim "  - amount: $REQUIRED_TOKEN ETH ($TOTAL_AMOUNT_WEI wei)"
else
    log_success "✓ Allowance sufficient"
fi
log_info ""

# Simulate bridging to each chain
log_dryrun "========================================="
log_dryrun "Simulating Bridge Transfers"
log_dryrun "========================================="
log_info ""

TOTAL_FEES=0
declare -a SIMULATED_TRANSFERS=()
declare -a FEE_INFO=()

for chain in "${!CHAIN_SELECTORS[@]}"; do
    selector="${CHAIN_SELECTORS[$chain]}"
    
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Chain: $chain"
    log_info "Selector: $selector"
    log_info ""
    
    # Calculate fee (read-only call)
    log_info "Calculating fee..."
    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"
        TOTAL_FEES=$(echo "scale=10; $TOTAL_FEES + $FEE_ETH" | bc 2>/dev/null || echo "0")
        FEE_INFO+=("$chain:$FEE_ETH")
    else
        log_warn "  Could not calculate fee (may need LINK tokens)"
        FEE_INFO+=("$chain:unknown")
    fi
    
    # Simulate the transfer
    log_sim "Would send transaction:"
    log_sim "  Contract: $BRIDGE_ADDRESS"
    log_sim "  Function: sendCrossChain(uint64,address,uint256)"
    log_sim "  Parameters:"
    log_sim "    - destinationChainSelector: $selector ($chain)"
    log_sim "    - receiver: $DEPLOYER"
    log_sim "    - amount: $AMOUNT ETH ($AMOUNT_WEI wei)"
    log_sim ""
    log_sim "Estimated gas: ~21000-100000 gas units"
    log_sim "Estimated gas cost: ~0.001-0.01 ETH (depending on gas price)"
    
    # Generate a simulated transaction hash (for display purposes)
    SIMULATED_HASH="0x$(openssl rand -hex 32 2>/dev/null || echo "0000000000000000000000000000000000000000000000000000000000000000")"
    SIMULATED_TRANSFERS+=("$chain:$SIMULATED_HASH")
    
    log_success "✓ Simulated transfer to $chain"
    log_info "  [SIMULATED] Transaction Hash: $SIMULATED_HASH"
    log_info ""
done

# Summary
log_dryrun "========================================="
log_dryrun "DRY-RUN Summary"
log_dryrun "========================================="
log_info ""
log_info "Configuration:"
log_info "  Token: $TOKEN_NAME"
log_info "  Amount per chain: $AMOUNT ETH"
log_info "  Total amount: $REQUIRED_TOKEN ETH"
log_info "  Number of chains: 7"
log_info ""

log_info "Current State:"
log_info "  ETH Balance: $ETH_BALANCE_ETH ETH"
log_info "  $TOKEN_NAME Balance: $TOKEN_BALANCE_ETH ETH"
log_info "  Bridge Allowance: $ALLOW_ETH ETH"
log_info ""

log_info "Required Actions:"
if (( $(echo "$TOKEN_BALANCE_ETH < $REQUIRED_TOKEN" | bc -l 2>/dev/null || echo 1) )); then
    WRAP_NEEDED=$(echo "scale=2; $REQUIRED_TOKEN - $TOKEN_BALANCE_ETH" | bc)
    log_warn "  1. Wrap $WRAP_NEEDED ETH to $TOKEN_NAME"
else
    log_success "  1. ✓ Sufficient $TOKEN_NAME balance (no wrap needed)"
fi

if (( $(echo "$ALLOW_ETH < $REQUIRED_TOKEN" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "  2. Approve bridge for $REQUIRED_TOKEN ETH"
else
    log_success "  2. ✓ Sufficient allowance (no approval needed)"
fi

log_info "  3. Send 7 bridge transactions (one per chain)"
log_info ""

log_info "Estimated Costs:"
log_info "  Token transfers: $REQUIRED_TOKEN ETH"
if [ "$TOTAL_FEES" != "0" ]; then
    log_info "  CCIP fees (LINK): ~$TOTAL_FEES ETH equivalent"
fi
log_info "  Gas fees (estimated): ~$ESTIMATED_GAS ETH"
log_info "  Total ETH needed: ~$TOTAL_NEEDED ETH"
log_info ""

log_info "Simulated Transaction Hashes:"
for entry in "${SIMULATED_TRANSFERS[@]}"; do
    chain=$(echo "$entry" | cut -d: -f1)
    hash=$(echo "$entry" | cut -d: -f2-)
    log_info "  $chain: $hash [SIMULATED]"
done
log_info ""

log_info "Fee Breakdown:"
for entry in "${FEE_INFO[@]}"; do
    chain=$(echo "$entry" | cut -d: -f1)
    fee=$(echo "$entry" | cut -d: -f2-)
    log_info "  $chain: $fee ETH"
done
log_info ""

log_warn "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_warn "⚠ THIS WAS A DRY-RUN - NO TRANSACTIONS WERE SENT"
log_warn "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info ""
log_info "To execute the actual bridge transfers, run:"
log_info "  ./bridge-to-all-7-chains.sh $TOKEN $AMOUNT"
log_info ""

