#!/usr/bin/env bash

# Check LINK Token Balance on ChainID 138
# Verifies that the admin wallet has LINK tokens for CCIP fees

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT" 2>/dev/null || true

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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"; }

if [[ -f "$PROJECT_ROOT/scripts/lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/scripts/lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env" 2>/dev/null || true
fi

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

CHAIN138_RPC="${RPC_URL_138:-http://192.168.11.211:8545}"
# Chain 138 LINK: 0xb7721d... (deployed on 138). Mainnet canonical is 0x51491077... — do not use mainnet address when checking balance on 138.
LINK_TOKEN="${LINK_TOKEN_138:-${LINK_TOKEN_CHAIN138:-0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03}}"

WALLET_ADDRESS=$(cast wallet address --private-key "$PRIVATE_KEY")

log_info "=== LINK Token Balance Check (ChainID 138) ==="
log_info "Wallet Address: $WALLET_ADDRESS"
log_info "LINK Token: $LINK_TOKEN"
log_info "RPC: $CHAIN138_RPC"
log_info ""

# Check if LINK token contract exists
log_info "Checking LINK token contract..."
LINK_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$CHAIN138_RPC" 2>/dev/null || echo "")
if [ -z "$LINK_CODE" ] || [ "${#LINK_CODE}" -lt 10 ]; then
    log_error "LINK token contract not found at $LINK_TOKEN"
    exit 1
fi
log_success "✓ LINK token contract found"

# Get LINK balance
log_info ""
log_info "Checking LINK balance..."
BALANCE_RAW=$(cast call "$LINK_TOKEN" "balanceOf(address)(uint256)" "$WALLET_ADDRESS" --rpc-url "$CHAIN138_RPC" 2>&1 || echo "ERROR")

if [[ "$BALANCE_RAW" == *"ERROR"* ]] || [[ "$BALANCE_RAW" == *"error"* ]]; then
    log_error "Failed to get balance: $BALANCE_RAW"
    exit 1
fi

# Convert to human readable (LINK has 18 decimals)
BALANCE_WEI=$(echo "$BALANCE_RAW" | tr -d '\n' | sed 's/^0x//')
BALANCE_DECIMAL=$(echo "scale=18; ibase=16; $(echo $BALANCE_WEI | tr '[:lower:]' '[:upper:]') / 10^12" | bc 2>/dev/null || echo "0")
BALANCE_LINK=$(echo "$BALANCE_RAW" | cast --to-unit wei ether 2>/dev/null || echo "$BALANCE_DECIMAL")

log_info ""
log_success "LINK Balance: $BALANCE_LINK LINK"
log_info "  Raw balance: $BALANCE_RAW"

# Check if balance is sufficient (recommended: at least 1 LINK for fees)
MIN_LINK="1.0"
BALANCE_NUMERIC=$(echo "$BALANCE_LINK" | sed 's/^0*//' || echo "0")

if (( $(echo "$BALANCE_LINK >= $MIN_LINK" | bc -l 2>/dev/null || echo "0") )); then
    log_success "✓ Balance is sufficient (>= $MIN_LINK LINK)"
    log_info ""
    log_info "Recommendation: Keep at least 1-2 LINK for CCIP fees"
    exit 0
else
    log_warn "⚠ Balance is low: $BALANCE_LINK LINK"
    log_warn "Recommended minimum: $MIN_LINK LINK"
    log_info ""
    log_info "You may need LINK tokens to pay CCIP fees for bridge operations."
    log_info ""
    log_info "To obtain LINK tokens on ChainID 138:"
    log_info "1. Bridge LINK from Mainnet to ChainID 138"
    log_info "2. Request LINK from network administrator"
    log_info "3. Check if LINK faucet is available"
    exit 1
fi
