#!/usr/bin/env bash
# Estimate CCIP fee for WETH9/10 bridge using calculateFee
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-estimate-fee.sh"
SCRIPT_DESC="Estimate CCIP fee for a WETH bridge to a destination chain"
SCRIPT_USAGE="${SCRIPT_NAME} --token {weth9|weth10} --selector <chainSelector> --amount <wei> [--rpc <url>] [--help]"
SCRIPT_OPTIONS="--token <name>     Bridge token type (weth9|weth10)\n--selector N       Destination chain selector (uint64)\n--amount WEI       Amount of token to send (wei)\n--rpc URL          RPC URL (default: ETHEREUM_MAINNET_RPC or public)\n--help             Show help"
SCRIPT_REQUIREMENTS="foundry cast, CCIP bridges deployed"
handle_help "${1:-}"

ensure_azure_cli >/dev/null 2>&1 || true

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

if [ -z "$TOKEN" ] || [ -z "$SELECTOR" ] || [ -z "$AMOUNT" ]; then
  log_error "Missing required args. See --help"
  exit 1
fi

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

log_info "Bridge: $BRIDGE_ADDR"
log_info "Selector: $SELECTOR"
log_info "Amount: $AMOUNT wei"

FEE=$(cast call --rpc-url "$RPC_URL" "$BRIDGE_ADDR" "calculateFee(uint64,uint256)(uint256)" "$SELECTOR" "$AMOUNT")
log_success "Estimated fee (feeToken): $FEE wei"
echo "$FEE"
