#!/usr/bin/env bash

set -e

# Manually relay a pending message from Chain 138 to Ethereum Mainnet
# This script can be used to test the relay mechanism or relay a specific message

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

# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

# Configuration
RPC_URL_138="${RPC_URL_138:-${RPC_URL:-http://192.168.11.250:8545}}"
RPC_URL_MAINNET="${RPC_URL_MAINNET:-https://eth.llamarpc.com}"
RELAY_ROUTER="${CCIP_RELAY_ROUTER_MAINNET:-0xAd9A228CcEB4cbB612cD165FFB72fE090ff10Afb}"
RELAY_BRIDGE="${CCIP_RELAY_BRIDGE_MAINNET:-0xF9A32F37099c582D28b4dE7Fca6eaC1e5259f939}"
SOURCE_ROUTER="${CCIP_ROUTER_CHAIN138:-0xd49B579DfC5912fA7CAa76893302c6e58f231431}"

# Message to relay (from transaction 0x69251f46df3ec0a4108f8faf97483527b289ce477d9628d2a8c15710c27b243d)
MESSAGE_ID="${1:-0xdf3c0df793fbd8c3dcd58f25fb22b4ff5800b9471f8f7680fba9515607707258}"

echo "=== Manual Message Relay ==="
echo ""
echo "Message ID: $MESSAGE_ID"
echo "Relay Router: $RELAY_ROUTER"
echo "Relay Bridge: $RELAY_BRIDGE"
echo ""

# Get message details from Chain 138
echo "Fetching message details from Chain 138..."
# Note: This would require querying the router's MessageSent event
# For now, we'll construct the message from known transaction data

# Known message details from transaction
DEST_CHAIN_SELECTOR="5009297550715157269"
SENDER="0xBBb4a9202716eAAB3644120001cC46096913a3C8"
RECIPIENT="0x4A666F96fC8764181194447A7dFdb7d471b301C8"
AMOUNT="20000000000000000000000"
WETH9_CHAIN138="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
SOURCE_CHAIN_SELECTOR="866240039685049171407962509760789466724431933144813155647626"

echo "Constructing relay message..."
echo "  Recipient: $RECIPIENT"
echo "  Amount: 20,000 WETH9"
echo ""

# Construct Any2EVMMessage
# This requires encoding the struct properly for the relay router call
echo "Relaying message to Ethereum Mainnet..."
echo ""

# Use cast to call relayMessage
# Note: This is complex due to struct encoding, so we'll use a Node.js script instead
echo "⚠️  Complex struct encoding required"
echo "   Using relay service or manual encoding needed"
echo ""
echo "Alternative: Start the relay service which will handle this automatically:"
echo "  cd services/relay"
echo "  npm start"

