#!/usr/bin/env bash
# CCIP Configure Destination Script
# Configures a remote bridge address for a specific chain selector
#
# Usage:
#   ./ccip-configure-destination.sh <chain-selector> <remote-bridge-address>
#
# Example (Chain 138 → Mainnet WETH9):
#   export BRIDGE_ADDRESS=$CCIPWETH9_BRIDGE_CHAIN138
#   ./ccip-configure-destination.sh 5009297550715157269 0x3304b747E565a97ec8AC220b0B6A1f6ffDB837e6

set -euo pipefail

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

# Load environment variables
ENV_FILE="${ENV_FILE:-$PROJECT_ROOT/.env}"
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | grep -E "^(RPC_URL|PRIVATE_KEY|CHAIN_ID|CCIP_ROUTER|LINK_TOKEN|WETH9_ADDRESS|WETH10_ADDRESS|CCIPWETH9_BRIDGE|CCIPWETH10_BRIDGE|ETHEREUM_MAINNET_SELECTOR|CHAIN138_SELECTOR)" | xargs)
fi

# Parse arguments
if [ $# -lt 2 ]; then
    echo "Usage: $0 <chain-selector> <remote-bridge-address>"
    echo ""
    echo "Arguments:"
    echo "  chain-selector        CCIP chain selector (e.g., 5009297550715157269 for Ethereum mainnet)"
    echo "  remote-bridge-address Address of the bridge contract on the destination chain"
    echo ""
    echo "Environment variables:"
    echo "  BRIDGE_ADDRESS       Address of the bridge contract to configure (required)"
    echo "  RPC_URL              RPC endpoint URL (required)"
    echo "  PRIVATE_KEY          Private key for signing transactions (required)"
    echo ""
    echo "Examples:"
    echo "  # Configure Chain 138 WETH9 bridge → Mainnet"
    echo "  export BRIDGE_ADDRESS=\$CCIPWETH9_BRIDGE_CHAIN138"
    echo "  $0 5009297550715157269 0x3304b747E565a97ec8AC220b0B6A1f6ffDB837e6"
    echo ""
    echo "  # Configure Mainnet WETH9 bridge → Chain 138"
    echo "  export BRIDGE_ADDRESS=\$CCIPWETH9_BRIDGE_MAINNET"
    echo "  $0 \$CHAIN138_SELECTOR 0x3304b747E565a97ec8AC220b0B6A1f6ffDB837e6"
    exit 1
fi

CHAIN_SELECTOR="$1"
REMOTE_BRIDGE="$2"

# Validate required environment variables
if [ -z "${BRIDGE_ADDRESS:-}" ]; then
    echo "Error: BRIDGE_ADDRESS not set"
    echo "Set it to the bridge contract address you want to configure:"
    echo "  export BRIDGE_ADDRESS=\$CCIPWETH9_BRIDGE_CHAIN138"
    echo "  # or"
    echo "  export BRIDGE_ADDRESS=\$CCIPWETH10_BRIDGE_CHAIN138"
    exit 1
fi

if [ -z "${RPC_URL:-}" ]; then
    echo "Error: RPC_URL not set"
    exit 1
fi

if [ -z "${PRIVATE_KEY:-}" ]; then
    echo "Error: PRIVATE_KEY not set"
    exit 1
fi

# Validate addresses
if ! cast --version &>/dev/null; then
    echo "Error: cast (Foundry) not found. Please install Foundry:"
    echo "  curl -L https://foundry.paradigm.xyz | bash"
    exit 1
fi

# Validate remote bridge address format
if ! cast --to-checksum-address "$REMOTE_BRIDGE" &>/dev/null; then
    echo "Error: Invalid remote bridge address: $REMOTE_BRIDGE"
    exit 1
fi

BRIDGE_ADDRESS=$(cast --to-checksum-address "$BRIDGE_ADDRESS")

echo "=========================================="
echo "CCIP Configure Destination"
echo "=========================================="
echo "Bridge Address: $BRIDGE_ADDRESS"
echo "Chain Selector: $CHAIN_SELECTOR"
echo "Remote Bridge: $REMOTE_BRIDGE"
echo "RPC URL: $RPC_URL"
echo ""

# Check if bridge contract exists
CODE=$(cast code "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -z "$CODE" ] || [ "$CODE" = "0x" ]; then
    echo "Error: No contract found at $BRIDGE_ADDRESS"
    exit 1
fi

# Verify current configuration (if possible)
echo "Checking current remote bridge configuration..."
CURRENT_REMOTE=$(cast call "$BRIDGE_ADDRESS" \
    "remoteBridges(uint64)(address)" \
    "$CHAIN_SELECTOR" \
    --rpc-url "$RPC_URL" 2>/dev/null || echo "0x0000000000000000000000000000000000000000")

if [ "$CURRENT_REMOTE" != "0x0000000000000000000000000000000000000000" ]; then
    echo "Current remote bridge: $CURRENT_REMOTE"
    if [ "$CURRENT_REMOTE" = "$REMOTE_BRIDGE" ]; then
        echo "✓ Remote bridge already configured correctly"
        exit 0
    else
        echo "⚠ Warning: Remote bridge is already set to a different address"
        read -p "Continue with update? [y/N]: " confirm
        if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
            echo "Aborted"
            exit 1
        fi
    fi
else
    echo "No remote bridge configured for this chain selector"
fi

echo ""
echo "Configuring destination..."
echo ""

# Call configureDestination function
cast send "$BRIDGE_ADDRESS" \
    "configureDestination(uint64,address)" \
    "$CHAIN_SELECTOR" \
    "$REMOTE_BRIDGE" \
    --private-key "$PRIVATE_KEY" \
    --rpc-url "$RPC_URL" \
    --gas-limit 200000

echo ""
echo "Waiting for transaction confirmation..."
sleep 5

# Verify configuration
VERIFIED_REMOTE=$(cast call "$BRIDGE_ADDRESS" \
    "remoteBridges(uint64)(address)" \
    "$CHAIN_SELECTOR" \
    --rpc-url "$RPC_URL" 2>/dev/null || echo "0x0000000000000000000000000000000000000000")

if [ "$VERIFIED_REMOTE" = "$REMOTE_BRIDGE" ]; then
    echo "✓ Configuration successful!"
    echo "  Chain Selector $CHAIN_SELECTOR → Remote Bridge $REMOTE_BRIDGE"
else
    echo "⚠ Warning: Configuration may not have been applied correctly"
    echo "  Expected: $REMOTE_BRIDGE"
    echo "  Got: $VERIFIED_REMOTE"
    exit 1
fi

echo ""
echo "=========================================="
echo "Configuration Complete"
echo "=========================================="

