#!/usr/bin/env bash
set -euo pipefail

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

source "$PROJECT_ROOT/scripts/lib/deployment/dotenv.sh"
load_deployment_env

if [[ -f "$PROJECT_ROOT/services/relay/.env.bsc" ]]; then
  set -a
  # shellcheck disable=SC1091
  source "$PROJECT_ROOT/services/relay/.env.bsc"
  set +a
fi

DRY_RUN=0
AMOUNT_WEI=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    *)
      if [[ -z "$AMOUNT_WEI" ]]; then
        AMOUNT_WEI="$1"
      fi
      shift
      ;;
  esac
done

RPC_URL="${DEST_RPC_URL:-${BSC_RPC_URL:-${BSC_MAINNET_RPC:-}}}"
BRIDGE_ADDRESS="${DEST_RELAY_BRIDGE:-}"
WETH_ADDRESS="${DEST_WETH9_ADDRESS:-0x2170Ed0880ac9A755fd29B2688956BD959F933F8}"

if [[ -z "${PRIVATE_KEY:-}" ]]; then
  echo "Set PRIVATE_KEY in .env" >&2
  exit 1
fi
if [[ -z "$RPC_URL" ]]; then
  echo "Set BSC_RPC_URL (or BSC_MAINNET_RPC / DEST_RPC_URL) in .env" >&2
  exit 1
fi
if [[ -z "$BRIDGE_ADDRESS" ]]; then
  echo "Set DEST_RELAY_BRIDGE in services/relay/.env.bsc" >&2
  exit 1
fi

DEPLOYER="$(cast wallet address --private-key "$PRIVATE_KEY")"

if [[ -z "$AMOUNT_WEI" ]]; then
  AMOUNT_WEI="$(cast call "$WETH_ADDRESS" "balanceOf(address)(uint256)" "$DEPLOYER" --rpc-url "$RPC_URL")"
fi

if [[ -z "$AMOUNT_WEI" || "$AMOUNT_WEI" == "0" ]]; then
  if [[ "$DRY_RUN" == "1" ]]; then
    AMOUNT_WEI="1000000000000000"
    echo "No BSC WETH available; using placeholder amount for dry-run: $AMOUNT_WEI wei"
  else
    echo "No BSC WETH available to fund the BSC relay bridge." >&2
    exit 1
  fi
fi

CMD=(cast send "$WETH_ADDRESS" "transfer(address,uint256)" "$BRIDGE_ADDRESS" "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --legacy)
DRY_CMD=(cast send "$WETH_ADDRESS" "transfer(address,uint256)" "$BRIDGE_ADDRESS" "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "<PRIVATE_KEY>" --legacy)

echo "BSC relay funding"
echo "  Deployer: $DEPLOYER"
echo "  WETH:     $WETH_ADDRESS"
echo "  Bridge:   $BRIDGE_ADDRESS"
echo "  Amount:   $AMOUNT_WEI wei"

if [[ "$DRY_RUN" == "1" ]]; then
  printf '  [DRY RUN] '
  printf '%q ' "${DRY_CMD[@]}"
  printf '\n'
  exit 0
fi

"${CMD[@]}"
