#!/usr/bin/env bash
# Redeploy Monad CCIPRelayBridge with canonical WMON (fixes wrong USDC address at 0x754704…).
#
# Usage: ./scripts/deployment/redeploy-monad-relay-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 relay bridge with WMON=$WMON_CANONICAL"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

[[ "$EXECUTE" == "1" ]] || { echo "Pass --execute"; exit 0; }
require_private_key_env || exit 1
command -v jq >/dev/null 2>&1 || { echo "jq required"; exit 1; }

RPC="${MONAD_MAINNET_RPC_PUBLIC:-https://rpc.monad.xyz}"
WMON_CANONICAL="${WMON_MAINNET:-0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A}"
ROUTER="${CCIP_RELAY_ROUTER_MONAD:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"

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

echo "=== Redeploy Monad CCIPRelayBridge (WMON=$WMON_CANONICAL) ==="

LOG="/tmp/monad-relay-bridge-wmon.log"
out=$(bash "$PROJECT_ROOT/scripts/forge/scope.sh" create relay contracts/relay/CCIPRelayBridge.sol:CCIPRelayBridge \
  --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
  --gas-limit 3500000 --broadcast \
  --constructor-args "$WMON_CANONICAL" "$ROUTER" 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; }

OK=$(cast call "$ROUTER" "authorizedBridges(address)(bool)" "$BRIDGE" --rpc-url "$RPC" 2>/dev/null || echo "false")
if [[ "$OK" != "true" ]]; then
  cast send "$ROUTER" "authorizeBridge(address)" "$BRIDGE" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 200000
fi

echo ""
echo "CCIP_RELAY_BRIDGE_MONAD=$BRIDGE"
echo "Update smom-dbis-138/.env and re-run wire-monad-chain138-relay.sh --execute"
