#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/init.sh"
load_env --file "$ROOT_DIR/.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="get-balance.sh"
SCRIPT_DESC="Query balance on ChainID 138 via Etherscan-like API"
SCRIPT_USAGE="${SCRIPT_NAME} --address <addr> [--apikey <key>] [--url <api>]"
SCRIPT_OPTIONS="--address ADDR     Address to query
--apikey KEY       API key (default: CHAIN138_ETHERSCAN_API_KEY)
--url URL          API base (default: CHAIN138_ETHERSCAN_API_URL)"
handle_help "${1:-}"

ADDR=""; KEY="${CHAIN138_ETHERSCAN_API_KEY:-}"; API="${CHAIN138_ETHERSCAN_API_URL:-}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --address) ADDR="$2"; shift 2;;
    --apikey) KEY="$2"; shift 2;;
    --url) API="$2"; shift 2;;
    --help) handle_help "--help";;
    *) log_error "Unknown arg: $1"; exit 1;;
  esac
done

[ -n "$ADDR" ] || { log_error "Missing --address"; exit 1; }
[ -n "$API" ] || { log_error "Set CHAIN138_ETHERSCAN_API_URL or pass --url"; exit 1; }
[ -n "$KEY" ] || { log_warn "No API key provided; request may be rate-limited"; }

URL="${API}?module=account&action=balance&address=${ADDR}&tag=latest${KEY:+&apikey=$KEY}"
curl -s "$URL" | jq .


