#!/usr/bin/env bash
# Check account balance via public RPC
# Usage: ./scripts/check-balance.sh [address] [rpc-url]

set -euo pipefail

ADDRESS="${1:-}"
RPC_URL="${2:-https://rpc-http-pub.d-bis.org}"

if [ -z "$ADDRESS" ]; then
    echo "Usage: $0 <address> [rpc-url]"
    echo "Example: $0 0x4a666f96fc8764181194447a7dfdb7d471b301c8"
    exit 1
fi

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "Checking balance for: $ADDRESS"
echo "RPC URL: $RPC_URL"
echo ""

RESPONSE=$(curl -s -X POST "$RPC_URL" \
    -H "Content-Type: application/json" \
    -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBalance\",\"params\":[\"$ADDRESS\",\"latest\"],\"id\":1}")

if echo "$RESPONSE" | jq -e '.error' >/dev/null 2>&1; then
    ERROR=$(echo "$RESPONSE" | jq -r '.error.message' 2>/dev/null || echo "Unknown error")
    echo "Error: $ERROR"
    exit 1
fi

BALANCE_HEX=$(echo "$RESPONSE" | jq -r '.result' 2>/dev/null)

if [ -z "$BALANCE_HEX" ] || [ "$BALANCE_HEX" = "null" ]; then
    echo "Error: Could not get balance"
    exit 1
fi

# Convert hex to wei using Python
BALANCE_WEI=$(python3 << PYEOF
balance_hex = "$BALANCE_HEX"
balance_wei = int(balance_hex, 16)
print(balance_wei)
PYEOF
)

# Convert wei to ETH
BALANCE_ETH=$(python3 << PYEOF
balance_wei = $BALANCE_WEI
balance_eth = balance_wei / 10**18
print(f"{balance_eth:.6f}")
PYEOF
)

echo "Balance (hex): $BALANCE_HEX"
echo "Balance (wei): $BALANCE_WEI"
echo -e "${GREEN}Balance (ETH): $BALANCE_ETH ETH${NC}"
echo ""

# Also show in other units
if [ "$BALANCE_WEI" != "0" ]; then
    BALANCE_GWEI=$(python3 << PYEOF
balance_wei = $BALANCE_WEI
balance_gwei = balance_wei / 10**9
print(f"{balance_gwei:.2f}")
PYEOF
)
    echo "Balance (Gwei): $BALANCE_GWEI Gwei"
fi

