#!/usr/bin/env bash
# Redeploy Monad outbound CCIPWETH9Bridge with canonical WMON on existing send router.
#
# Usage: ./scripts/deployment/redeploy-monad-send-bridge-wmon.sh --execute

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
while [[ $# -gt 0 ]]; do
  case "$1" in
    --execute) EXECUTE=1; shift ;;
    --dry-run) echo "[DRY RUN] redeploy Monad send bridge"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

[[ "$EXECUTE" == "1" ]] || { echo "Pass --execute"; exit 0; }
require_private_key_env || exit 1

RPC="${MONAD_MAINNET_RPC_PUBLIC:-https://rpc.monad.xyz}"
WMON="${WMON_MAINNET:-0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A}"
ROUTER="${CCIP_ROUTER_MONAD_SEND:-0x937824f2516fa58f25aeAb92E7BFf7D74F463B4c}"
FEE="${CCIP_FEE_TOKEN:-0x0000000000000000000000000000000000000000}"
CH138_SEL="${CHAIN138_SELECTOR:-16015286601757825753}"
CH138_BRIDGE="${CCIP_RELAY_BRIDGE_CHAIN138_WETH:-}"

sym=$(cast call "$WMON" "symbol()(string)" --rpc-url "$RPC" 2>/dev/null | tr -d '"' || echo "?")
[[ "$sym" == "WMON" ]] || { echo "ERROR: $WMON symbol=$sym (expected WMON)" >&2; exit 1; }

echo "=== Redeploy Monad outbound CCIPWETH9Bridge ==="
echo "Router: $ROUTER  WMON: $WMON"

LOG="/tmp/monad-send-bridge-wmon.log"
out=$(bash "$PROJECT_ROOT/scripts/forge/scope.sh" create ccip contracts/ccip/CCIPWETH9Bridge.sol:CCIPWETH9Bridge \
  --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
  --gas-limit 5000000 --broadcast \
  --constructor-args "$ROUTER" "$WMON" "$FEE" 2>&1) || {
  printf '%s\n' "$out" | tee "$LOG"
  exit 1
}
printf '%s\n' "$out" | tee "$LOG"

BRIDGE=$(printf '%s\n' "$out" | sed -n 's/.*Deployed to: \(0x[0-9a-fA-F]\{40\}\).*/\1/p' | head -1)
[[ -n "$BRIDGE" ]] || { echo "ERROR: parse bridge address failed" >&2; exit 1; }

if [[ -n "$CH138_BRIDGE" ]]; then
  enabled=$(cast call "$BRIDGE" "destinations(uint64)(uint64,address,bool)" "$CH138_SEL" --rpc-url "$RPC" 2>/dev/null | awk 'NR==3{print $1}')
  if [[ "$enabled" != "true" ]]; then
    cast send "$BRIDGE" "addDestination(uint64,address)" "$CH138_SEL" "$CH138_BRIDGE" \
      --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 300000
  else
    cast send "$BRIDGE" "updateDestination(uint64,address)" "$CH138_SEL" "$CH138_BRIDGE" \
      --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 300000
  fi
fi

echo ""
echo "CCIPWETH9_BRIDGE_MONAD_SEND=$BRIDGE"
