#!/usr/bin/env bash

# Find ChainID 138 CCIP Selector
# This script helps determine the ChainID 138 CCIP selector

set -e

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

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

# Load environment variables
# Default matches operator LAN Core RPC (see project AGENTS.md / rules).
CHAIN138_RPC="${RPC_URL_138:-http://192.168.11.211:8545}"
CHAIN138_RPC="${CHAIN138_RPC%$'\r'}"
CHAIN138_RPC="${CHAIN138_RPC%$'\n'}"
CCIP_ROUTER_138="${CCIP_ROUTER_138:-0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817}"

log_info "=== Finding ChainID 138 CCIP Selector ==="
log_info "RPC: $CHAIN138_RPC"
log_info ""

# Method 1: Check if selector is documented in networks.json
log_info "Method 1: Checking networks.json..."
if [ -f "$PROJECT_ROOT/networks.json" ]; then
    SELECTOR=$(cat "$PROJECT_ROOT/networks.json" | grep -A 1 '"138"' | grep '"chainSelector"' | cut -d'"' -f4)
    if [ -n "$SELECTOR" ]; then
        log_success "Found selector in networks.json: $SELECTOR"
        echo ""
        echo "To use this selector, add to .env:"
        echo "CHAIN138_SELECTOR=$SELECTOR"
        exit 0
    fi
fi

# Method 2: Query Chainlink CCIP Directory (if available)
log_info "Method 2: Querying Chainlink CCIP Directory..."
log_warn "Note: CCIP Directory query requires API access or on-chain query"

# Method 3: Calculate or use chain ID directly (for custom implementations)
log_info "Method 3: Checking for custom selector calculation..."
log_warn "For custom CCIP implementations, selector may be the chain ID itself: 138"
log_warn "For official Chainlink CCIP, selector must be obtained from CCIP Directory"

# Method 4: Check environment files
log_info "Method 4: Checking environment files..."
if [ -f "$PROJECT_ROOT/.env" ]; then
    SELECTOR=$(grep "CHAIN138_SELECTOR" "$PROJECT_ROOT/.env" | cut -d'=' -f2 | tr -d ' ' | tr -d '"')
    if [ -n "$SELECTOR" ] && [ "$SELECTOR" != "" ]; then
        log_success "Found selector in .env: $SELECTOR"
        exit 0
    fi
fi

echo ""
log_warn "ChainID 138 selector not found automatically"
log_info ""
log_info "To find the selector:"
log_info "1. Query Chainlink CCIP Directory: https://docs.chain.link/ccip/supported-networks"
log_info "2. Check ChainID 138 CCIP Router documentation"
log_info "3. For custom implementations, selector may be chain ID (138)"
log_info ""
log_info "Once found, add to .env:"
log_info "CHAIN138_SELECTOR=<selector-value>"
