#!/usr/bin/env bash
# Show CCIP bridge status/config
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
load_env --file "$SCRIPT_DIR/../../.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="ccip-status.sh"
SCRIPT_DESC="Display CCIP WETH bridge configuration and status"
SCRIPT_USAGE="${SCRIPT_NAME} --token {weth9|weth10} [--user <address>] [--rpc <url>] [--help]"
SCRIPT_OPTIONS="--token <name>     Bridge token type (weth9|weth10)\n--user ADDR       Show nonce for user\n--rpc URL          RPC URL (default: ETHEREUM_MAINNET_RPC or public)\n--help             Show help"
SCRIPT_REQUIREMENTS="foundry cast"
handle_help "${1:-}"

TOKEN=""; USER=""; RPC_URL="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2;;
    --user) USER="$2"; shift 2;;
    --rpc) RPC_URL="$2"; shift 2;;
    --help) handle_help "--help";;
    *) log_error "Unknown arg: $1"; exit 1;;
  esac
done

case "$TOKEN" in
  weth9) BRIDGE_ADDR="${CCIPWETH9_BRIDGE_MAINNET:?set in .env}";;
  weth10) BRIDGE_ADDR="${CCIPWETH10_BRIDGE_MAINNET:?set in .env}";;
  *) log_error "--token required as weth9|weth10"; exit 1;;
esac

log_section "CCIP STATUS ($TOKEN)"
echo "Bridge: $BRIDGE_ADDR"
printf "ccipRouter: %s\n" "$(cast call --rpc-url "$RPC_URL" "$BRIDGE_ADDR" "ccipRouter()(address)")"
printf "feeToken:   %s\n" "$(cast call --rpc-url "$RPC_URL" "$BRIDGE_ADDR" "feeToken()(address)")"
echo
echo "Destination chains:"
selectors_json=$(cast call --rpc-url "$RPC_URL" "$BRIDGE_ADDR" "getDestinationChains()(uint64[])" | sed 's/^\[\|\]$//g')
if [ -z "$selectors_json" ]; then
  echo "  (none)"
else
  IFS=',' read -ra arr <<< "$selectors_json"
  for s in "${arr[@]}"; do
    s_trim="$(echo "$s" | xargs)"
    echo "  - $s_trim"
  done
fi

if [ -n "$USER" ]; then
  echo
  printf "User nonce (%s): %s\n" "$USER" "$(cast call --rpc-url "$RPC_URL" "$BRIDGE_ADDR" "getUserNonce(address)(uint256)" "$USER")"
fi
log_success "OK"
