#!/usr/bin/env bash

# Check Mainnet ETH and LINK balances for deployment

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
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 "=== Mainnet Wallet Balance Check ==="

# Check if cast is available
if ! command -v cast &> /dev/null; then
    log_error "Error: cast (Foundry) not found. Please install Foundry."
    exit 1
fi

# Get wallet address from private key
if ! require_private_key_env; then
    exit 1
fi

WALLET_ADDRESS="$(derive_deployer_address || true)"
if [ -z "$WALLET_ADDRESS" ]; then
    log_error "ERROR: Could not derive DEPLOYER_ADDRESS from PRIVATE_KEY."
    exit 1
fi

log_info "Wallet Address: $WALLET_ADDRESS"

# Mainnet RPC
MAINNET_RPC_URL="${MAINNET_RPC_URL:-${ETHEREUM_MAINNET_RPC:-}}"
if [ -z "$MAINNET_RPC_URL" ]; then
    MAINNET_RPC_URL="https://eth.llamarpc.com"
fi

# Mainnet LINK token address
MAINNET_LINK="0x514910771AF9Ca656af840dff83E8264EcF986CA"

# Required amounts
ETH_RECOMMENDED="50000000000000000"  # 0.05 ETH
LINK_RECOMMENDED="10000000000000000000"  # 10 LINK
ETH_REQUIRED="${ETH_REQUIRED:-${MAINNET_ETH_REQUIRED:-25000000000000000}}"  # 0.025 ETH

log_info "=== Mainnet ETH Balance ==="

# Check ETH balance
ETH_BALANCE=$(cast balance "$WALLET_ADDRESS" --rpc-url "$MAINNET_RPC_URL" 2>/dev/null || echo "0")
ETH_AMOUNT=$(cast --to-unit "$ETH_BALANCE" ether 2>/dev/null || echo "0")

echo "Balance: $ETH_AMOUNT ETH"
echo "Required: 0.025 ETH (minimum)"
echo "Recommended: 0.05 ETH (with buffer)"

# Check if sufficient
if [ "$(echo "$ETH_BALANCE >= $ETH_REQUIRED" | bc 2>/dev/null || echo "0")" == "1" ]; then
    log_success "✅ Status: Sufficient ETH for deployment"
    ETH_PASS=true
else
    log_error "❌ Status: Insufficient ETH"
    DEFICIT=$(echo "$ETH_REQUIRED - $ETH_BALANCE" | bc 2>/dev/null || echo "$ETH_REQUIRED")
    DEFICIT_ETH=$(cast --to-unit "$DEFICIT" ether 2>/dev/null || echo "0.025")
    log_warn "Need: $DEFICIT_ETH ETH more"
    ETH_PASS=false
fi


log_info "=== Mainnet LINK Balance ==="

# Check LINK balance
LINK_BALANCE=$(cast call "$MAINNET_LINK" "balanceOf(address)(uint256)" "$WALLET_ADDRESS" --rpc-url "$MAINNET_RPC_URL" 2>/dev/null || echo "0")
if [[ "$LINK_BALANCE" =~ ^0x ]]; then
    LINK_BALANCE=$(cast --to-dec "$LINK_BALANCE" 2>/dev/null || echo "0")
fi
LINK_BALANCE="$(printf '%s' "$LINK_BALANCE" | tr -d '\r\n[:space:]')"
if [[ -z "$LINK_BALANCE" || ! "$LINK_BALANCE" =~ ^[0-9]+$ ]]; then
    LINK_BALANCE="0"
fi

if [ "$LINK_BALANCE" != "0" ] && [ -n "$LINK_BALANCE" ]; then
    LINK_AMOUNT=$(cast --to-unit "$LINK_BALANCE" ether 2>/dev/null || echo "0")
    echo "Balance: $LINK_AMOUNT LINK"
else
    echo "Balance: 0 LINK"
    LINK_AMOUNT="0"
fi

echo "Required: 0 LINK (not needed for deployment)"
echo "Recommended: 10 LINK (for CCIP fees and testing)"

# Check if sufficient (LINK is optional)
if [ "$(echo "$LINK_BALANCE >= $LINK_RECOMMENDED" | bc 2>/dev/null || echo "0")" == "1" ]; then
    log_success "✅ Status: Sufficient LINK for CCIP fees"
    LINK_PASS=true
elif [ "$LINK_BALANCE" != "0" ] && [ -n "$LINK_BALANCE" ]; then
    log_warn "⚠️  Status: LINK available but below recommended amount"
    LINK_PASS=true  # Still pass, just a warning
else
    log_warn "⚠️  Status: No LINK (not required for deployment)"
    log_warn "Note: LINK is only needed for CCIP fees when users bridge tokens"
    LINK_PASS=true  # Pass because LINK is optional for deployment
fi


# Summary
log_info "=== Summary ==="

if [ "$ETH_PASS" == "true" ]; then
    log_success "✅ ETH: Sufficient for Mainnet deployment"
else
    log_error "❌ ETH: Insufficient - Please fund wallet"
    echo "Send ETH to: $WALLET_ADDRESS"
    echo "Amount needed: $DEFICIT_ETH ETH"
fi

if [ "$LINK_PASS" == "true" ] && [ "$LINK_AMOUNT" != "0" ]; then
    log_success "✅ LINK: Available for CCIP fees"
elif [ "$LINK_PASS" == "true" ]; then
    log_warn "⚠️  LINK: Not available (optional for deployment)"
fi


if [ "$ETH_PASS" == "true" ]; then
    log_success "✅ Ready for Mainnet deployment!"
    echo "You can proceed with:"
    echo "  ./scripts/deployment/deploy-bridges-mainnet.sh"
    exit 0
else
    log_error "❌ Not ready for Mainnet deployment"
    echo "Please fund your wallet:"
    echo "  Address: $WALLET_ADDRESS"
    echo "  Amount: $DEFICIT_ETH ETH minimum (0.05 ETH recommended)"
    exit 1
fi
