#!/usr/bin/env bash
# Print the live unload routes from Chain 138 to reachable public chains.
#
# This helper does not send transactions. It reviews the current WETH9 bridge
# topology, classifies each public-chain lane, and prints exact cast command
# packs for the current amount/recipient.
#
# Usage:
#   ./scripts/deployment/print-chain138-public-chain-unload-routes.sh
#
# Optional env:
#   TARGET_CHAIN=gnosis
#   UNLOAD_AMOUNT_WEI=10000000000000000
#   RECIPIENT=0x...
#   OPTIONAL_UNWRAP_WEI=2000000000000000

set -euo pipefail

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

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

need_var() {
  local name="$1"
  [[ -n "${!name:-}" ]] || {
    echo "Error: $name is required" >&2
    exit 1
  }
}

trim_word() {
  echo "$1" | awk '{print $1}'
}

fmt_ether() {
  local raw="${1:-0}"
  raw="$(trim_word "$raw")"
  cast from-wei "$raw" ether 2>/dev/null || echo "$raw"
}

contains_true() {
  [[ "$1" == *", true)"* ]]
}

extract_addr() {
  echo "$1" | grep -oE '0x[a-fA-F0-9]{40}' | head -n1 | tr '[:upper:]' '[:lower:]'
}

extract_enabled_addr() {
  local raw="$1"
  local addr
  addr="$(extract_addr "$raw")"
  if contains_true "$raw" && [[ -n "$addr" ]]; then
    echo "$addr"
  else
    echo ""
  fi
}

query_dest() {
  local rpc="$1"
  local bridge="$2"
  local selector="$3"
  if [[ -z "$rpc" || -z "$bridge" || -z "$selector" ]]; then
    echo "UNSET"
    return 0
  fi
  cast call "$bridge" 'destinations(uint64)((uint64,address,bool))' "$selector" --rpc-url "$rpc" 2>/dev/null || echo "ERROR"
}

quote_fee_state() {
  local rpc="$1"
  local bridge="$2"
  local selector="$3"
  if [[ -z "$rpc" || -z "$bridge" || -z "$selector" ]]; then
    echo "n/a"
    return 0
  fi
  if cast call "$bridge" 'calculateFee(uint64,uint256)(uint256)' "$selector" 4000000000000000 --rpc-url "$rpc" >/dev/null 2>&1; then
    echo "quoted"
  else
    echo "blocked"
  fi
}

balance_of() {
  local rpc="$1"
  local token="$2"
  local wallet="$3"
  if [[ -z "$rpc" || -z "$token" || -z "$wallet" ]]; then
    echo "0"
    return 0
  fi
  cast call "$token" 'balanceOf(address)(uint256)' "$wallet" --rpc-url "$rpc" 2>/dev/null | awk '{print $1}' || echo "0"
}

native_balance() {
  local rpc="$1"
  if [[ -z "$rpc" ]]; then
    echo "0"
    return 0
  fi
  cast balance "$DEPLOYER" --rpc-url "$rpc" 2>/dev/null || echo "0"
}

env_value_from_file() {
  local file="$1"
  local key="$2"
  [[ -f "$file" ]] || {
    echo ""
    return 0
  }
  grep -E "^${key}=" "$file" | head -n1 | cut -d'=' -f2- | tr -d ' "\r\n' || true
}

relay_inventory_note() {
  local inventory_raw="$1"
  if [[ "$(echo "$inventory_raw >= $UNLOAD_AMOUNT_WEI" | bc)" == "1" ]]; then
    echo "enough-for-request"
  elif [[ "$(echo "$inventory_raw > 0" | bc)" == "1" ]]; then
    echo "small-only"
  else
    echo "empty"
  fi
}

practical_route_label() {
  local name="$1"
  local mainnet_quote_state="$2"
  case "$name" in
    mainnet|bsc|avalanche) echo "relay-backed-direct" ;;
    wemix) echo "blocked" ;;
    *)
      if [[ "$mainnet_quote_state" == "blocked" ]]; then
        echo "mainnet-hub-blocked"
      else
        echo "via-mainnet-hub"
      fi
      ;;
  esac
}

prereq_text() {
  local name="$1"
  local practical_route="$2"
  local inventory_state="$3"
  local mainnet_dest_enabled="$4"

  case "$practical_route" in
    relay-backed-direct)
      case "$inventory_state" in
        enough-for-request) echo "inventory ready" ;;
        small-only) echo "inventory only covers tiny unloads" ;;
        empty)
          if [[ "$name" == "mainnet" ]]; then
            echo "seed mainnet relay bridge WETH"
          else
            echo "seed relay bridge WETH"
          fi
          ;;
      esac
      ;;
    via-mainnet-hub)
      if [[ "$mainnet_dest_enabled" == "enabled" ]]; then
        echo "bootstrap mainnet first"
      else
        echo "fix mainnet destination mapping first"
      fi
      ;;
    mainnet-hub-blocked)
      echo "repair Mainnet WETH9 source bridge quote/send path first"
      ;;
    *)
      echo "deploy bridge and seed gas"
      ;;
  esac
}

best_use_text() {
  local name="$1"
  local practical_route="$2"
  local inventory_state="$3"
  local mainnet_dest_enabled="$4"

  case "$practical_route" in
    relay-backed-direct)
      case "$name" in
        mainnet)
          if [[ "$inventory_state" == "enough-for-request" ]]; then
            echo "direct 138 -> mainnet unload"
          else
            echo "bootstrap mainnet through the proven BSC recovery path, then keep relay inventory topped up"
          fi
          ;;
        bsc)
          if [[ "$inventory_state" == "enough-for-request" ]]; then
            echo "direct 138 -> BSC unload"
          elif [[ "$inventory_state" == "small-only" ]]; then
            echo "tiny direct 138 -> BSC unloads; use mainnet hub for larger funding"
          else
            echo "seed BSC relay inventory or fund BSC from mainnet hub"
          fi
          ;;
        avalanche)
          if [[ "$inventory_state" == "enough-for-request" ]]; then
            echo "direct 138 -> Avalanche unload"
          else
            echo "seed Avalanche relay inventory or fund Avalanche from mainnet hub"
          fi
          ;;
      esac
      ;;
    via-mainnet-hub)
      if [[ "$mainnet_dest_enabled" == "enabled" ]]; then
        echo "bootstrap mainnet, then send mainnet -> $name"
      else
        echo "repair mainnet -> $name mapping before using the hub"
      fi
      ;;
    mainnet-hub-blocked)
      echo "blocked until the Mainnet WETH9 source bridge/router quote path is repaired"
      ;;
    *)
      echo "deploy and wire WEMIX first"
      ;;
  esac
}

print_source_send_commands() {
  local name="$1"
  local selector="$2"
  local upper
  upper="$(echo "$name" | tr '[:lower:]-' '[:upper:]_')"

  cat <<EOF
export FEE_${upper}_WEI=\$(cast call "$CCIPWETH9_BRIDGE_CHAIN138" "calculateFee(uint64,uint256)(uint256)" \\
  "$selector" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$RPC_URL_138" | awk '{print \$1}')
echo "FEE_${upper}_WEI=\$FEE_${upper}_WEI"

cast send "$WETH9_138" "approve(address,uint256)" \\
  "$CCIPWETH9_BRIDGE_CHAIN138" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$RPC_URL_138" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy --gas-price 2000000000

cast send "$LINK_138" "approve(address,uint256)" \\
  "$CCIPWETH9_BRIDGE_CHAIN138" "\$FEE_${upper}_WEI" \\
  --rpc-url "\$RPC_URL_138" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy --gas-price 2000000000

cast send "$CCIPWETH9_BRIDGE_CHAIN138" "sendCrossChain(uint64,address,uint256)" \\
  "$selector" "\$RECIPIENT" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$RPC_URL_138" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy --gas-limit 900000 --gas-price 2000000000
EOF
}

print_unwrap_commands() {
  local wrapped_token="$1"
  local rpc="$2"
  [[ -n "$wrapped_token" && -n "$rpc" ]] || return 0

  cat <<EOF
# Optional: unwrap a little of the received wrapped-native token into gas.
cast send "$wrapped_token" "withdraw(uint256)" \\
  "$OPTIONAL_UNWRAP_WEI" \\
  --rpc-url "$rpc" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy
EOF
}

print_mainnet_send_commands() {
  local name="$1"
  local selector="$2"
  local wrapped_token="$3"
  local rpc="$4"
  local upper
  upper="$(echo "$name" | tr '[:lower:]-' '[:upper:]_')"

  cat <<EOF
# After mainnet is funded, fan out from the mainnet WETH9 bridge:
export FEE_MAINNET_TO_${upper}_WEI=\$(cast call "$MAINNET_CCIP_WETH9_BRIDGE" "calculateFee(uint64,uint256)(uint256)" \\
  "$selector" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$ETHEREUM_MAINNET_RPC" | awk '{print \$1}')
echo "FEE_MAINNET_TO_${upper}_WEI=\$FEE_MAINNET_TO_${upper}_WEI"

cast send "$MAINNET_WETH9" "approve(address,uint256)" \\
  "$MAINNET_CCIP_WETH9_BRIDGE" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$ETHEREUM_MAINNET_RPC" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy
EOF

  if [[ "${MAINNET_FEE_TOKEN,,}" != "${ZERO_ADDRESS,,}" ]]; then
    cat <<EOF

cast send "$MAINNET_FEE_TOKEN" "approve(address,uint256)" \\
  "$MAINNET_CCIP_WETH9_BRIDGE" "\$FEE_MAINNET_TO_${upper}_WEI" \\
  --rpc-url "\$ETHEREUM_MAINNET_RPC" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy

cast send "$MAINNET_CCIP_WETH9_BRIDGE" "sendCrossChain(uint64,address,uint256)" \\
  "$selector" "\$RECIPIENT" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$ETHEREUM_MAINNET_RPC" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy --gas-limit 900000
EOF
  else
    cat <<EOF

cast send "$MAINNET_CCIP_WETH9_BRIDGE" "sendCrossChain(uint64,address,uint256)" \\
  "$selector" "\$RECIPIENT" "$UNLOAD_AMOUNT_WEI" \\
  --rpc-url "\$ETHEREUM_MAINNET_RPC" \\
  --private-key "\$PRIVATE_KEY" \\
  --legacy --gas-limit 900000 --value "\$FEE_MAINNET_TO_${upper}_WEI"
EOF
  fi

  if [[ -n "$wrapped_token" && -n "$rpc" ]]; then
    echo ""
    print_unwrap_commands "$wrapped_token" "$rpc"
  fi
}

need_var PRIVATE_KEY
need_var RPC_URL_138
need_var CCIPWETH9_BRIDGE_CHAIN138
need_var ETH_MAINNET_SELECTOR
need_var MAINNET_CCIP_WETH9_BRIDGE
need_var ETHEREUM_MAINNET_RPC

DEPLOYER="$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || true)"
[[ -n "$DEPLOYER" ]] || {
  echo "Error: could not derive deployer from PRIVATE_KEY" >&2
  exit 1
}

WETH9_138="$(cast call "$CCIPWETH9_BRIDGE_CHAIN138" 'weth9()(address)' --rpc-url "$RPC_URL_138" | tail -n1)"
LINK_138="$(cast call "$CCIPWETH9_BRIDGE_CHAIN138" 'feeToken()(address)' --rpc-url "$RPC_URL_138" | tail -n1)"
MAINNET_WETH9="$(cast call "$MAINNET_CCIP_WETH9_BRIDGE" 'weth9()(address)' --rpc-url "$ETHEREUM_MAINNET_RPC" | tail -n1)"
MAINNET_FEE_TOKEN="$(cast call "$MAINNET_CCIP_WETH9_BRIDGE" 'feeToken()(address)' --rpc-url "$ETHEREUM_MAINNET_RPC" | tail -n1)"

ZERO_ADDRESS="0x0000000000000000000000000000000000000000"
CHAIN138_SELECTOR_VALUE="${CHAIN138_SELECTOR:-138}"
CURRENT_138_WETH9="${CCIPWETH9_BRIDGE_CHAIN138,,}"
LEGACY_138_WETH9="${CCIPWETH9_BRIDGE_DIRECT_LEGACY:-0x971cD9D156f193df8051E48043C476e53ECd4693}"
LEGACY_138_WETH9="${LEGACY_138_WETH9,,}"
TARGET_CHAIN="${TARGET_CHAIN:-all}"
UNLOAD_AMOUNT_WEI="${UNLOAD_AMOUNT_WEI:-10000000000000000}"
OPTIONAL_UNWRAP_WEI="${OPTIONAL_UNWRAP_WEI:-2000000000000000}"
RECIPIENT="${RECIPIENT:-$DEPLOYER}"

RELAY_DIR="$PROJECT_ROOT/services/relay"
BSC_RELAY_PROFILE="$RELAY_DIR/.env.bsc"
AVAX_RELAY_PROFILE="$RELAY_DIR/.env.avax"

CHAINS=(
  "mainnet|${ETH_MAINNET_SELECTOR:-}|${ETHEREUM_MAINNET_RPC:-}|${MAINNET_CCIP_WETH9_BRIDGE:-}|$MAINNET_WETH9|${CCIP_RELAY_BRIDGE_MAINNET:-}|$RELAY_DIR/.env"
  "bsc|${BSC_SELECTOR:-}|${BSC_MAINNET_RPC:-}|${CCIPWETH9_BRIDGE_BSC:-}|${WETH9_BSC:-}|0x886C6A4ABC064dbf74E7caEc460b7eeC31F1b78C|$BSC_RELAY_PROFILE"
  "avalanche|${AVALANCHE_SELECTOR:-}|${AVALANCHE_MAINNET_RPC:-}|${CCIPWETH9_BRIDGE_AVALANCHE:-}|${WETH9_AVALANCHE:-}|0x3f8C409C6072a2B6a4Ff17071927bA70F80c725F|$AVAX_RELAY_PROFILE"
  "gnosis|${GNOSIS_SELECTOR:-}|${GNOSIS_RPC:-}|${CCIPWETH9_BRIDGE_GNOSIS:-}|${WETH9_GNOSIS:-}||"
  "cronos|${CRONOS_SELECTOR:-}|${CRONOS_RPC:-}|${CCIPWETH9_BRIDGE_CRONOS:-}|${WETH9_CRONOS:-}||"
  "celo|${CELO_SELECTOR:-1346049177634351622}|${CELO_RPC:-}|${CCIPWETH9_BRIDGE_CELO:-}|${WETH9_CELO:-}||"
  "polygon|${POLYGON_SELECTOR:-}|${POLYGON_MAINNET_RPC:-}|${CCIPWETH9_BRIDGE_POLYGON:-}|${WETH9_POLYGON:-}||"
  "arbitrum|${ARBITRUM_SELECTOR:-}|${ARBITRUM_MAINNET_RPC:-}|${CCIPWETH9_BRIDGE_ARBITRUM:-}|${WETH9_ARBITRUM:-}||"
  "optimism|${OPTIMISM_SELECTOR:-}|${OPTIMISM_MAINNET_RPC:-}|${CCIPWETH9_BRIDGE_OPTIMISM:-}|${WETH9_OPTIMISM:-}||"
  "base|${BASE_SELECTOR:-}|${BASE_MAINNET_RPC:-}|${CCIPWETH9_BRIDGE_BASE:-}|${WETH9_BASE:-}||"
  "wemix|${WEMIX_SELECTOR:-5142893604156789321}|${WEMIX_RPC:-}|${CCIPWETH9_BRIDGE_WEMIX:-}|${WETH9_WEMIX:-}||"
)

echo "# Chain 138 Public-Chain Unload Routes"
echo "# Generated: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
echo "# Deployer: $DEPLOYER"
echo "# Recipient: $RECIPIENT"
echo "# Unload amount: $UNLOAD_AMOUNT_WEI ($(fmt_ether "$UNLOAD_AMOUNT_WEI"))"
echo "# Optional unwrap amount: $OPTIONAL_UNWRAP_WEI ($(fmt_ether "$OPTIONAL_UNWRAP_WEI"))"
echo "# WETH9 rail only. WETH10 remains drifted and is intentionally excluded."
echo ""

printf '%-10s | %-22s | %-28s | %-34s\n' "Chain" "Practical Route" "Live Prerequisite" "Best Use"
printf '%s\n' "------------------------------------------------------------------------------------------------------------------------"

for entry in "${CHAINS[@]}"; do
  IFS='|' read -r name selector rpc native_bridge wrapped_token relay_bridge relay_profile <<< "$entry"
  if [[ "$TARGET_CHAIN" != "all" && "$TARGET_CHAIN" != "$name" ]]; then
    continue
  fi

  source_dest="$(query_dest "$RPC_URL_138" "$CCIPWETH9_BRIDGE_CHAIN138" "$selector")"
  source_addr="$(extract_enabled_addr "$source_dest")"
  route_type="disabled"
  if [[ -n "$source_addr" && -n "$native_bridge" && "$source_addr" == "${native_bridge,,}" ]]; then
    route_type="direct-native"
  elif [[ -n "$source_addr" && -n "$relay_bridge" && "$source_addr" == "${relay_bridge,,}" ]]; then
    route_type="relay-backed"
  elif [[ -n "$source_addr" ]]; then
    route_type="other:$source_addr"
  elif [[ -z "$native_bridge" ]]; then
    route_type="deploy-first"
  fi

  inventory_raw="0"
  if [[ "$route_type" == "relay-backed" && -n "$wrapped_token" && -n "$relay_bridge" && -n "$rpc" ]]; then
    inventory_raw="$(balance_of "$rpc" "$wrapped_token" "$relay_bridge")"
  fi
  inventory_state="$(relay_inventory_note "$inventory_raw")"
  mainnet_route_to_target="$(query_dest "$ETHEREUM_MAINNET_RPC" "$MAINNET_CCIP_WETH9_BRIDGE" "$selector")"
  mainnet_dest_enabled="disabled"
  mainnet_quote_state="n/a"
  if [[ "$name" != "mainnet" ]]; then
    mainnet_quote_state="$(quote_fee_state "$ETHEREUM_MAINNET_RPC" "$MAINNET_CCIP_WETH9_BRIDGE" "$selector")"
  fi
  if contains_true "$mainnet_route_to_target"; then
    mainnet_dest_enabled="enabled"
  fi
  practical_route="$(practical_route_label "$name" "$mainnet_quote_state")"
  prereq="$(prereq_text "$name" "$practical_route" "$inventory_state" "$mainnet_dest_enabled")"
  best_use="$(best_use_text "$name" "$practical_route" "$inventory_state" "$mainnet_dest_enabled")"
  printf '%-10s | %-22s | %-28s | %-34s\n' "$name" "$practical_route" "$prereq" "$best_use"
done

echo ""

for entry in "${CHAINS[@]}"; do
  IFS='|' read -r name selector rpc native_bridge wrapped_token relay_bridge relay_profile <<< "$entry"
  if [[ "$TARGET_CHAIN" != "all" && "$TARGET_CHAIN" != "$name" ]]; then
    continue
  fi

  source_dest="$(query_dest "$RPC_URL_138" "$CCIPWETH9_BRIDGE_CHAIN138" "$selector")"
  source_addr="$(extract_enabled_addr "$source_dest")"
  route_type="disabled"
  if [[ -n "$source_addr" && -n "$native_bridge" && "$source_addr" == "${native_bridge,,}" ]]; then
    route_type="direct-native"
  elif [[ -n "$source_addr" && -n "$relay_bridge" && "$source_addr" == "${relay_bridge,,}" ]]; then
    route_type="relay-backed"
  elif [[ -n "$source_addr" ]]; then
    route_type="other:$source_addr"
  elif [[ -z "$native_bridge" ]]; then
    route_type="deploy-first"
  fi

  inventory_raw="0"
  inventory_state="empty"
  if [[ "$route_type" == "relay-backed" && -n "$wrapped_token" && -n "$relay_bridge" && -n "$rpc" ]]; then
    inventory_raw="$(balance_of "$rpc" "$wrapped_token" "$relay_bridge")"
    inventory_state="$(relay_inventory_note "$inventory_raw")"
  fi

  mainnet_route_to_target="$(query_dest "$ETHEREUM_MAINNET_RPC" "$MAINNET_CCIP_WETH9_BRIDGE" "$selector")"
  mainnet_dest_enabled="disabled"
  mainnet_dest_addr="$(extract_enabled_addr "$mainnet_route_to_target")"
  mainnet_quote_state="n/a"
  if [[ "$name" != "mainnet" ]]; then
    mainnet_quote_state="$(quote_fee_state "$ETHEREUM_MAINNET_RPC" "$MAINNET_CCIP_WETH9_BRIDGE" "$selector")"
  fi
  if [[ "$name" == "mainnet" ]]; then
    mainnet_dest_enabled="n/a"
    mainnet_dest_addr="n/a"
  elif contains_true "$mainnet_route_to_target"; then
    mainnet_dest_enabled="enabled"
  fi
  practical_route="$(practical_route_label "$name" "$mainnet_quote_state")"

  remote_to_mainnet="$(query_dest "$rpc" "$native_bridge" "$ETH_MAINNET_SELECTOR")"
  remote_to_138="$(query_dest "$rpc" "$native_bridge" "$CHAIN138_SELECTOR_VALUE")"
  mainnet_enabled="disabled"
  back_addr="$(extract_enabled_addr "$remote_to_138")"
  return_state="missing"
  if contains_true "$remote_to_mainnet"; then
    mainnet_enabled="enabled"
  fi
  if [[ -n "$back_addr" ]]; then
    if [[ "$back_addr" == "$CURRENT_138_WETH9" ]]; then
      return_state="current"
    elif [[ "$back_addr" == "$LEGACY_138_WETH9" ]]; then
      return_state="legacy"
    else
      return_state="$back_addr"
    fi
  fi

  echo "## $name"
  echo "- Chain 138 mapping: $route_type"
  echo "- Chain 138 destination: ${source_addr:-disabled}"
  echo "- Practical route today: $practical_route"
  if [[ -n "$wrapped_token" ]]; then
    echo "- Destination wrapped asset: $wrapped_token"
  fi
  if [[ -n "$rpc" ]]; then
    echo "- Deployer native gas on destination: $(fmt_ether "$(native_balance "$rpc")")"
  fi
  if [[ "$route_type" == "relay-backed" ]]; then
    echo "- Relay bridge inventory: $(fmt_ether "$inventory_raw")"
    echo "- Request coverage at current amount: $(relay_inventory_note "$inventory_raw")"
  fi
  if [[ "$mainnet_enabled" == "enabled" ]]; then
    echo "- Mainnet fan-out from this chain: enabled"
  elif [[ "$name" != "mainnet" && -n "$native_bridge" ]]; then
    echo "- Mainnet fan-out from this chain: disabled"
  fi
  if [[ "$name" != "mainnet" && -n "$native_bridge" ]]; then
    echo "- Return path to Chain 138: $return_state"
  fi
  echo "- Mainnet hub destination: ${mainnet_dest_addr:-disabled} ($mainnet_dest_enabled)"
  if [[ "$name" != "mainnet" ]]; then
    echo "- Mainnet hub quote preflight: $mainnet_quote_state"
  fi
  echo "- Best use today: $(best_use_text "$name" "$practical_route" "$inventory_state" "$mainnet_dest_enabled")"
  echo ""

  if [[ "$practical_route" == "relay-backed-direct" ]]; then
    echo "Exact Chain 138 send commands:"
    print_source_send_commands "$name" "$selector"
    echo ""
    if [[ -n "$relay_profile" && -f "$relay_profile" ]]; then
      relay_name="$(basename "$relay_profile")"
      if [[ "$name" == "mainnet" ]]; then
        cat <<EOF
# Relay worker for this lane:
cd "$RELAY_DIR"
./start-relay.sh
EOF
      elif [[ "$name" == "bsc" || "$name" == "avalanche" ]]; then
        profile_name="${name/avalanche/avax}"
        cat <<EOF
# Relay worker for this lane:
cd "$RELAY_DIR"
./start-relay.sh "$profile_name"
EOF
      fi
      echo "# Relay profile file: $relay_name"
    fi
  else
    if [[ "$name" == "wemix" ]]; then
      echo "No unload commands printed because the WEMIX bridge is not deployed in env."
    else
      echo "The native Chain 138 mapping is not the practical route of truth here."
      echo "Why: Chain 138 emits through a custom router that only creates events; it does not natively deliver into these public CCIP bridges."
      echo "Proof point: the earlier 138 -> Gnosis native-bridge attempt failed for exactly this reason."
      echo ""
      if [[ "$mainnet_dest_enabled" == "enabled" && "$mainnet_quote_state" == "quoted" ]]; then
        echo "Exact mainnet hub commands:"
        echo "# First bootstrap mainnet. If the mainnet relay bridge is empty, reuse the proven BSC relay plus external bridge recovery flow."
        print_mainnet_send_commands "$name" "$selector" "$wrapped_token" "$rpc"
      elif [[ "$mainnet_dest_enabled" == "enabled" ]]; then
        echo "Mainnet exposes an enabled destination for $name, but the current Mainnet WETH9 source bridge quote path is blocked."
        echo "Do not broadcast mainnet fan-out sends until the source bridge/router path is repaired or replaced."
      else
        echo "Mainnet does not currently expose an enabled destination for $name, so the hub route must be repaired first."
      fi
    fi
  fi

  echo ""
done
