#!/usr/bin/env bash
# List all tokens in the deployer wallet across all networks.
# Token categories (see docs/11-references/TOKEN_CATEGORIES_CANONICAL.md):
#   1. Canonical 138 Compliant: Native ETH, WETH, WETH10, LINK, cUSDT, cUSDC, cEURT, cEURC, cGBPT, cGBPC, cAUDT, cAUDC, cJPYT, cJPYC, cCHFT, cCHFC, cCADT, cCADC, cAUSDT
#   2. ALL Mainnet (Alltra): Native, AUSDT, USDT, USDC, WETH, WALL
#   3. Compliant Wrapped (cW*): cWUSDT, cWUSDC, cWEURT, cWEURC, ... (per public chain)
#   4. D-WIN W Tokens: USDW, EURW, GBPW, AUDW, JPYW, CHFW, CADW (Cronos §4)
# This script lists (1) Chain 138, (2) ALL Mainnet, (4) Cronos D-WIN W, plus Ethereum/Polygon/Base/Optimism/BSC/Avalanche/Arbitrum.
# Uses PRIVATE_KEY or DEPLOYER_ADDRESS; falls back to public RPCs when env RPC vars unset.
#
# Usage: ./scripts/deployment/list-deployer-tokens-all-networks.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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

if [ -f .env ]; then
  set -a
  source .env
  set +a
fi

# Deployer: derive from PRIVATE_KEY or use DEPLOYER_ADDRESS if set (read-only mode)
if [ -n "${DEPLOYER_ADDRESS:-}" ]; then
  DEPLOYER="${DEPLOYER_ADDRESS}"
  [[ "$DEPLOYER" != 0x* ]] && DEPLOYER="0x$DEPLOYER"
else
  if [ -z "${PRIVATE_KEY:-}" ]; then
    echo "ERROR: Set PRIVATE_KEY in .env or DEPLOYER_ADDRESS=0x4A666F96fC8764181194447A7dFdb7d471b301C8 for read-only"
    exit 1
  fi
  DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || true)
  if [ -z "$DEPLOYER" ]; then
    echo "ERROR: Could not derive deployer address (is 'cast' available?)"
    exit 1
  fi
fi

# Format raw balance with decimals (divide by 10^decimals). Uses cast when decimals=18.
format_balance() {
  local raw="$1"
  local decimals="${2:-18}"
  if [ -z "$raw" ] || [ "$raw" = "0" ]; then
    echo "0"
    return
  fi
  if [ "$decimals" = "18" ]; then
    cast --to-unit "$raw" ether 2>/dev/null || echo "$raw"
    return
  fi
  # bc: 10^decimals (e.g. 10^6 for USDC)
  echo "scale=12; $raw / 10^$decimals" | bc 2>/dev/null | sed 's/^\./0./;s/0*$//;s/\.$//' || echo "$raw"
}

# Fetch ERC-20 balance and decimals, print "  SYMBOL: balance"
token_balance_line() {
  local rpc="$1"
  local token_addr="$2"
  local symbol="$3"
  local decimals_override="${4:-}"
  local bal_hex
  bal_hex=$(cast call "$token_addr" "balanceOf(address)(uint256)" "$DEPLOYER" --rpc-url "$rpc" 2>/dev/null || echo "0x0")
  local bal_raw
  bal_raw=$(cast --to-dec "$bal_hex" 2>/dev/null || echo "0")
  if [ -z "$decimals_override" ]; then
    decimals_override=$(cast call "$token_addr" "decimals()(uint8)" --rpc-url "$rpc" 2>/dev/null | cast --to-dec 2>/dev/null || echo "18")
  fi
  local disp
  disp=$(format_balance "$bal_raw" "$decimals_override")
  printf "  %-8s %s\n" "$symbol:" "$disp"
}

# Report one network: native + optional ERC-20 list (name, rpc, chain_id, native_symbol, "addr:symbol:decimals ...")
report_network() {
  local name="$1"
  local rpc="$2"
  local chain_id="$3"
  local native_sym="$4"
  local token_list="$5"

  echo ""
  echo "=== $name (chain $chain_id) ==="
  if [ -z "$rpc" ]; then
    echo "  (no RPC configured)"
    return
  fi
  local native_wei
  native_wei=$(cast balance "$DEPLOYER" --rpc-url "$rpc" 2>/dev/null || echo "0")
  local native_disp
  native_disp=$(cast --to-unit "$native_wei" ether 2>/dev/null || echo "0")
  echo "  Native ($native_sym): $native_disp"

  local entry addr rest sym dec
  for entry in $token_list; do
    entry=$(echo "$entry" | tr -d '[:space:]')
    [ -z "$entry" ] && continue
    addr="${entry%%:*}"
    rest="${entry#*:}"
    sym="${rest%%:*}"
    dec="${rest#*:}"
    [ "$dec" = "$rest" ] && dec=""
    token_balance_line "$rpc" "$addr" "$sym" "$dec"
  done
}

echo "============================================"
echo "Deployer wallet tokens (all networks)"
echo "Deployer: $DEPLOYER"
echo "============================================"

# Fallback public RPCs when env not set (so token lists are always shown)
RPC_138="${RPC_URL_138:-https://rpc-core.d-bis.org}"
RPC_1="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
RPC_651940="${CHAIN_651940_RPC:-${ALLTRA_MAINNET_RPC:-https://mainnet-rpc.alltra.global}}"
RPC_25="${CRONOS_RPC:-${CRONOS_MAINNET_RPC:-https://evm.cronos.org}}"
RPC_137="${POLYGON_MAINNET_RPC:-https://polygon-rpc.com}"
RPC_8453="${BASE_MAINNET_RPC:-https://mainnet.base.org}"
RPC_10="${OPTIMISM_MAINNET_RPC:-https://mainnet.optimism.io}"
RPC_56="${BSC_RPC_URL:-${BSC_MAINNET_RPC:-https://bsc-dataseed.binance.org}}"
RPC_43114="${AVALANCHE_RPC_URL:-${AVALANCHE_MAINNET_RPC:-https://api.avax.network/ext/bc/C/rpc}}"
RPC_42161="${ARBITRUM_MAINNET_RPC:-https://arb1.arbitrum.io/rpc}"

# Chain 138 tokens (from CHAIN138_TOKEN_ADDRESSES)
CHAIN138_TOKENS="
  0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2:WETH:18
  0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f:WETH10:18
  0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03:LINK:18
  0x93E66202A11B1772E55407B32B44e5Cd8eda7f22:cUSDT:6
  0xf22258f57794CC8E06237084b353Ab30fFfa640b:cUSDC:6
  0x15DF1D5BFDD8Aa4b380445D4e3E9B38d34283619:USDT:6
"
report_network "Chain 138" "$RPC_138" "138" "ETH" "$CHAIN138_TOKENS"

# Ethereum Mainnet
MAINNET_TOKENS="
  0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2:WETH:18
  0xdAC17F958D2ee523a2206206994597C13D831ec7:USDT:6
  0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48:USDC:6
  0x514910771AF9Ca656af840dff83E8264EcF986CA:LINK:18
  0x6B175474E89094C44Da98b954EedeAC495271d0F:DAI:18
"
report_network "Ethereum Mainnet" "$RPC_1" "1" "ETH" "$MAINNET_TOKENS"

# ALL Mainnet (651940)
ALLMAINNET_TOKENS="
  0x015B1897Ed5279930bC2Be46F661894d219292A6:AUSDT:18
  0x66D8Efa0AF63B0e84eb1Dd72bf00f00cd1e2234e:USDT:18
  0xa95EeD79f84E6A0151eaEb9d441F9Ffd50e8e881:USDC:18
  0x798F6762BB40d6801A593459d08F890603D3979C:WETH:18
  0x2da2b8f961F161ab6320acB3377e2e844a3C3ce4:WALL:18
"
report_network "ALL Mainnet (Alltra)" "$RPC_651940" "651940" "ETH" "$ALLMAINNET_TOKENS"

# Cronos (25)
CRONOS_TOKENS="
  0x99B3511A2d315A497C8112C1fdd8D508d4B1E506:WETH9:18
  0x3304b747E565a97ec8AC220b0B6A1f6ffDB837e6:WETH10:18
  0x8c80A01F461f297Df7F9DA3A4f740D7297C8Ac85:LINK:18
  0x948690147D2e50ffe50C5d38C14125aD6a9FA036:USDW:2
  0x58a8D8F78F1B65c06dAd7542eC46b299629A60dd:EURW:2
  0xFb4B6Cc81211F7d886950158294A44C312abCA29:GBPW:2
  0xf9f5D0ACD71C76F9476F10B3F3d3E201F0883C68:AUDW:2
  0xeE17bB0322383fecCA2784fbE2d4CD7d02b1905B:JPYW:2
  0xc9750828124D4c10e7a6f4B655cA8487bD3842EB:CHFW:2
  0x328Cd365Bb35524297E68ED28c6fF2C9557d1363:CADW:2
"
report_network "Cronos" "$RPC_25" "25" "CRO" "$CRONOS_TOKENS"

# Polygon
POLYGON_TOKENS="
  0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619:WETH:18
  0xc2132D05D31c914a87C6611C10748AEb04B58e8F:USDT:6
  0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174:USDC:6
  0xb0897686c545045aFc77CF20eA7Ee945E98F291e:LINK:18
"
report_network "Polygon" "$RPC_137" "137" "MATIC" "$POLYGON_TOKENS"

# Base
BASE_TOKENS="
  0x4200000000000000000000000000000000000006:WETH:18
  0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913:USDC:6
  0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb:DAI:18
"
report_network "Base" "$RPC_8453" "8453" "ETH" "$BASE_TOKENS"

# Optimism
OPTIMISM_TOKENS="
  0x4200000000000000000000000000000000000006:WETH:18
  0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85:USDC:6
  0x94b008aA00579c1307B0EF2c499aD98a8ce58e58:USDT:6
"
report_network "Optimism" "$RPC_10" "10" "ETH" "$OPTIMISM_TOKENS"

# BSC (56)
BSC_TOKENS="
  0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173c095c:WBNB:18
  0x55d398326f99059fF775485246999027B3197955:USDT:18
  0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d:USDC:18
  0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c:BTCB:18
"
report_network "BSC (BNB Chain)" "$RPC_56" "56" "BNB" "$BSC_TOKENS"

# Avalanche C-Chain
AVAX_TOKENS="
  0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7:WAVAX:18
  0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7:USDT:6
  0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E:USDC:6
"
report_network "Avalanche C-Chain" "$RPC_43114" "43114" "AVAX" "$AVAX_TOKENS"

# Arbitrum One
ARBITRUM_TOKENS="
  0x82aF49447D8a07e3bd95BD0d56f35241523fBab1:WETH:18
  0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9:USDT:6
  0xaf88d065e77c8cC2239327C5EDb3A432268e5831:USDC:6
"
report_network "Arbitrum One" "$RPC_42161" "42161" "ETH" "$ARBITRUM_TOKENS"

# Sepolia (optional; no token list)
report_network "Ethereum Sepolia" "${ETHEREUM_SEPOLIA_RPC:-}" "11155111" "ETH" ""

# Polygon Amoy
report_network "Polygon Amoy" "${POLYGON_AMOY_RPC:-}" "80002" "MATIC" ""

# Base Sepolia
report_network "Base Sepolia" "${BASE_SEPOLIA_RPC:-}" "84532" "ETH" ""

# Optimism Sepolia
report_network "Optimism Sepolia" "${OPTIMISM_SEPOLIA_RPC:-}" "11155420" "ETH" ""

echo ""
echo "============================================"
echo "Done. Override RPCs via .env: RPC_URL_138, ETHEREUM_MAINNET_RPC, CHAIN_651940_RPC, CRONOS_RPC, etc."
echo "============================================"
