#!/usr/bin/env bash
# Deploy CCIPRelayRouter + CCIPRelayBridge on Monad (143) for 138→Monad delivery.
#
# Usage:
#   DRY_RUN=1 ./scripts/deployment/deploy-monad-ccip-relay.sh
#   ./scripts/deployment/deploy-monad-ccip-relay.sh --execute
#
# Records: CCIP_RELAY_ROUTER_MONAD, CCIP_RELAY_BRIDGE_MONAD in .env

set -euo pipefail

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

# shellcheck disable=SC1090
source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
load_deployment_env --repo-root "$PROJECT_ROOT"

EXECUTE=0
DRY_RUN="${DRY_RUN:-0}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --execute) EXECUTE=1; shift ;;
    --dry-run) DRY_RUN=1; shift ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

RPC="${MONAD_MAINNET_RPC:-https://rpc.monad.xyz}"
if [[ "$RPC" =~ infura\.io/v3 ]] && [[ "${MONAD_MAINNET_RPC_FORCE_INFURA:-0}" != "1" ]]; then
  RPC="${MONAD_MAINNET_RPC_PUBLIC:-https://rpc.monad.xyz}"
fi

WMON="${WETH9_MONAD:-${WMON_MAINNET:-0x754704bc059f8c67012fed69bc8a327a5aafb603}}"
RELAYER="${RELAYER_ADDRESS:-${DEPLOYER_ADDRESS:-0x4A666F96fC8764181194447A7dFdb7d471b301C8}}"

export WETH9_MAINNET="$WMON"
export RELAYER_ADDRESS="$RELAYER"

echo "=== Deploy CCIP relay on Monad (143) ==="
echo "RPC: ${RPC%%\?*}"
echo "WMON (relay bridge token): $WMON"
echo "Relayer: $RELAYER"

if [[ "$DRY_RUN" == "1" || "$EXECUTE" != "1" ]]; then
  echo "[DRY RUN] forge script script/DeployCCIPRelay.s.sol:DeployCCIPRelay --rpc-url $RPC --chain-id 143 --broadcast --legacy"
  [[ "$EXECUTE" != "1" && "$DRY_RUN" != "1" ]] && echo "Pass --execute to broadcast."
  exit 0
fi

require_private_key_env || exit 1
"$SCRIPT_DIR/preflight-monad-deploy.sh"

LOG="/tmp/monad-ccip-relay-deploy.log"
forge script script/DeployCCIPRelay.s.sol:DeployCCIPRelay \
  --rpc-url "$RPC" \
  --chain-id 143 \
  --private-key "$PRIVATE_KEY" \
  --broadcast --legacy -vvv 2>&1 | tee "$LOG"

ROUTER=$(grep -oE "CCIPRelayRouter deployed at: 0x[a-fA-F0-9]{40}" "$LOG" | grep -oE "0x[a-fA-F0-9]{40}" | tail -1)
BRIDGE=$(grep -oE "CCIPRelayBridge deployed at: 0x[a-fA-F0-9]{40}" "$LOG" | grep -oE "0x[a-fA-F0-9]{40}" | tail -1)

if [[ -z "$ROUTER" || -z "$BRIDGE" ]]; then
  echo "ERROR: could not parse relay addresses from $LOG" >&2
  exit 1
fi

echo ""
echo "CCIP_RELAY_ROUTER_MONAD=$ROUTER"
echo "CCIP_RELAY_BRIDGE_MONAD=$BRIDGE"
echo ""
echo "Add to smom-dbis-138/.env and re-run complete-config / wire-monad scripts."
