#!/usr/bin/env bash
# Run all deployment tests

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi


log_info "=== Running All Deployment Tests ==="

# Load environment
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

MAINNET_RPC="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
CHAIN138_RPC="${RPC_URL:-https://rpc.d-bis.org}"

echo "1. Verifying contract deployments..."
"$SCRIPT_DIR/verify-mainnet-deployments.sh" 2>&1 | tail -10

echo "2. Checking bridge configurations..."
WETH9_MAINNET=$(grep "CCIPWETH9_BRIDGE_MAINNET=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")
if [ -n "$WETH9_MAINNET" ]; then
    echo "   Checking WETH9 Bridge destinations..."
    cast call "$WETH9_MAINNET" "getDestination(uint64)" "0x000000000000008a" --rpc-url "$MAINNET_RPC" 2>&1 | grep -E "0x[0-9a-f]{40}" && echo "   ✅ Chain-138 destination configured" || echo "   ⚠️  Chain-138 destination not configured"
fi

echo "3. Checking balances..."
WALLET=$(cast wallet address "${PRIVATE_KEY:-0x0}" 2>/dev/null || echo "")
if [ -n "$WALLET" ] && [ "$WALLET" != "0x0" ]; then
    BALANCE=$(cast balance "$WALLET" --rpc-url "$MAINNET_RPC" 2>/dev/null || echo "0")
    BALANCE_ETH=$(echo "scale=6; $BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
    echo "   Wallet balance: $BALANCE_ETH ETH"
fi

log_success "✅ Test suite complete"
