#!/usr/bin/env bash

# Shared helpers for the canonical CCIP destination matrix.

_ccip_dest_helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EXPLORER_PROJECT_ROOT="${EXPLORER_PROJECT_ROOT:-$(cd "$_ccip_dest_helper_dir/../.." && pwd)}"
CCIP_DESTINATION_MATRIX_FILE="${CCIP_DESTINATION_MATRIX_FILE:-$EXPLORER_PROJECT_ROOT/config/ccip-destination-matrix.json}"

ccip_destination_rows() {
    if [ ! -f "$CCIP_DESTINATION_MATRIX_FILE" ]; then
        echo "Missing CCIP destination matrix: $CCIP_DESTINATION_MATRIX_FILE" >&2
        return 1
    fi
    if ! command -v jq >/dev/null 2>&1; then
        echo "jq is required to read $CCIP_DESTINATION_MATRIX_FILE" >&2
        return 1
    fi
    jq -r '.chains[] | [.name, (.selector | tostring), (.weth9Bridge // ""), (.weth10Bridge // ""), (.rpcUrl // "")] | @tsv' \
        "$CCIP_DESTINATION_MATRIX_FILE"
}

ccip_destination_count() {
    if [ ! -f "$CCIP_DESTINATION_MATRIX_FILE" ] || ! command -v jq >/dev/null 2>&1; then
        return 1
    fi
    jq '.chains | length' "$CCIP_DESTINATION_MATRIX_FILE"
}

ccip_destination_field_by_name() {
    local chain_name="${1:-}"
    local field_name="${2:-}"
    if [ -z "$chain_name" ] || [ -z "$field_name" ] || [ ! -f "$CCIP_DESTINATION_MATRIX_FILE" ] || ! command -v jq >/dev/null 2>&1; then
        return 1
    fi
    jq -r --arg name "$chain_name" --arg field "$field_name" \
        '.chains[] | select(.name == $name) | .[$field] // empty' \
        "$CCIP_DESTINATION_MATRIX_FILE"
}

ccip_destination_selector_by_name() {
    local chain_name="${1:-}"
    ccip_destination_field_by_name "$chain_name" selector
}
