#!/usr/bin/env bash
# Print cast commands to configure CCIPWETH10Bridge (Mainnet ↔ Chain 138).
# For hands-off execution use execute-bridge-config.sh (WETH9 + WETH10).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[[ -f "$SCRIPT_DIR/../lib/init.sh" ]] && source "$SCRIPT_DIR/../lib/init.sh" 2>/dev/null || true
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

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 [[ -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
fi

MAINNET_RPC="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
MAINNET_RPC="${MAINNET_RPC%$'\r'}"
MAINNET_RPC="${MAINNET_RPC%$'\n'}"
CHAIN138_RPC="${RPC_URL_138:-${CHAIN138_RPC:-http://192.168.11.211:8545}}"
CHAIN138_RPC="${CHAIN138_RPC%$'\r'}"
CHAIN138_RPC="${CHAIN138_RPC%$'\n'}"

PRIVATE_KEY="${PRIVATE_KEY:-}"
[[ -n "$PRIVATE_KEY" && ! "$PRIVATE_KEY" =~ ^0x ]] && PRIVATE_KEY="0x$PRIVATE_KEY"

WETH10_BRIDGE_MAINNET=$(grep "CCIPWETH10_BRIDGE_MAINNET=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "\r\n' || echo "${CCIPWETH10_BRIDGE_MAINNET:-}")
WETH10_BRIDGE_CHAIN138=$(grep "CCIPWETH10_BRIDGE_CHAIN138=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "\r\n' || echo "${CCIPWETH10_BRIDGE_CHAIN138:-}")

CHAIN138_SELECTOR="${CHAIN138_SELECTOR:-138}"
ETH_SELECTOR="${ETH_MAINNET_SELECTOR:-5009297550715157269}"

WETH10_BRIDGE_MAINNET="${WETH10_BRIDGE_MAINNET,,}"
WETH10_BRIDGE_CHAIN138="${WETH10_BRIDGE_CHAIN138,,}"

if [[ -z "$WETH10_BRIDGE_MAINNET" || -z "$WETH10_BRIDGE_CHAIN138" ]]; then
  echo "Error: Set CCIPWETH10_BRIDGE_MAINNET and CCIPWETH10_BRIDGE_CHAIN138 in .env" >&2
  exit 1
fi

echo "=== CCIPWETH10Bridge — run these cast commands (decimal selectors) ==="
echo ""
echo "# On Ethereum mainnet (add Chain 138 as destination):"
echo "cast send ${WETH10_BRIDGE_MAINNET} \"addDestination(uint64,address)\" ${CHAIN138_SELECTOR} ${WETH10_BRIDGE_CHAIN138} \\"
echo "  --rpc-url ${MAINNET_RPC} --private-key \"\$PRIVATE_KEY\" --legacy --gas-limit 400000"
echo ""
echo "# On Chain 138 (add Mainnet as destination):"
echo "cast send ${WETH10_BRIDGE_CHAIN138} \"addDestination(uint64,address)\" ${ETH_SELECTOR} ${WETH10_BRIDGE_MAINNET} \\"
echo "  --rpc-url ${CHAIN138_RPC} --private-key \"\$PRIVATE_KEY\" --legacy --gas-limit 250000 --gas-price 2000000000"
echo ""
echo "Or run: ./scripts/deployment/execute-bridge-config.sh"
