#!/usr/bin/env bash

# Check LINK Token Balance at Specific Address
# Usage: ./check-link-balance-at-address.sh [LINK_TOKEN_ADDRESS]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# 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"; }

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

# LINK token address (use provided or documented deployment)
LINK_TOKEN="${1:-0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03}"
CHAIN138_RPC="${RPC_URL_138:-http://192.168.11.211:8545}"
WALLET=$(cast wallet address --private-key "$PRIVATE_KEY")

log_info "=== LINK Token Balance Check ==="
log_info "LINK Token: $LINK_TOKEN"
log_info "Wallet: $WALLET"
log_info ""

# Check balance
BALANCE_RAW=$(cast call "$LINK_TOKEN" "balanceOf(address)(uint256)" "$WALLET" --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 LINK (18 decimals) - handle both hex and decimal formats
if [[ "$BALANCE_RAW" == *"["* ]]; then
    # Extract the decimal value from [9.999e23] format
    BALANCE_WEI=$(echo "$BALANCE_RAW" | sed 's/.*\[\([0-9.e+-]*\)\].*/\1/' | sed 's/e+23/e23/')
    BALANCE_LINK=$(python3 -c "print(float('$BALANCE_WEI') / 10**18)")
else
    # Handle raw hex or decimal string
    BALANCE_WEI=$(echo "$BALANCE_RAW" | tr -d '\n' | sed 's/^0x//')
    if [[ "$BALANCE_WEI" =~ ^[0-9]+$ ]]; then
        # Already decimal
        BALANCE_LINK=$(python3 -c "print(int('$BALANCE_WEI') / 10**18)")
    else
        # Hex format
        BALANCE_DECIMAL=$(cast --to-dec "0x$BALANCE_WEI" 2>/dev/null || echo "0")
        BALANCE_LINK=$(python3 -c "print(int('$BALANCE_DECIMAL') / 10**18)")
    fi
fi

log_success "LINK Balance: $BALANCE_LINK LINK"
log_info "Raw balance (wei): $BALANCE_RAW"

if (( $(echo "$BALANCE_LINK >= 1.0" | bc -l 2>/dev/null || echo "0") )); then
    log_success "✓ Sufficient balance for CCIP fees"
    exit 0
else
    log_warn "⚠ Low balance: $BALANCE_LINK LINK (recommended: >= 1 LINK)"
    log_info ""
    log_info "To transfer LINK tokens to this wallet:"
    log_info "1. Check if LINK exists in another account"
    log_info "2. Transfer using: cast send $LINK_TOKEN 'transfer(address,uint256)' $WALLET <amount_wei> --rpc-url $CHAIN138_RPC --private-key <sender_key>"
    exit 1
fi
