#!/bin/bash

BASEPATH="$(dirname "$0")"
json_file="${BASEPATH}/reference-rpc-endpoint.json"

# Check if JSON file exists
if [ ! -f "$json_file" ]; then
    # Fallback for legacy path
    json_file="/root/rpc/reference-rpc-endpoint.json"
fi
if [ ! -f "$json_file" ]; then
    echo "JSON file not found: $json_file"
    exit 1
fi

# Look up urls by registry key (drpc slug from the compose x-upstreams chain label).
# Works for non-EVM chains that have no chainid in the registry.
if [ "$1" = "--chain" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 --chain <slug>"
        exit 1
    fi
    urls=$(jq -r --arg k "$2" '.[$k].urls // [] | .[]' "$json_file" 2>/dev/null | tr '\n' ' ')
    if [ -z "${urls// /}" ]; then
        echo "Chain not found: $2"
        exit 1
    fi
    echo "$urls"
    exit 0
fi

# Look up the protocol family for a registry key (eth, starknet, aztec, bitcoin, solana, ...)
if [ "$1" = "--protocol" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 --protocol <slug>"
        exit 1
    fi
    protocol=$(jq -r --arg k "$2" 'if has($k) then (.[$k].protocol // "eth") else empty end' "$json_file" 2>/dev/null)
    if [ -z "$protocol" ]; then
        echo "Chain not found: $2"
        exit 1
    fi
    echo "$protocol"
    exit 0
fi

# Look up the expected block time (milliseconds) for a registry key (drpc slug) or chain id.
# Used by sync-status.sh / check-health.sh to scale the lag thresholds per chain.
if [ "$1" = "--block-time-ms" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 --block-time-ms <slug|chainid>"
        exit 1
    fi
    key="$2"
    # Try by slug first
    bt=$(jq -r --arg k "$key" '.[$k].block_time_ms // empty' "$json_file" 2>/dev/null)
    if [ -z "$bt" ]; then
        # Fall back to lookup by chain id (decimal; convert hex)
        idk="$key"
        [[ "$idk" == 0x* ]] && idk=$(printf "%d" "$idk" 2>/dev/null)
        if [[ "$idk" =~ ^[0-9]+$ ]]; then
            bt=$(jq -r --arg id "$idk" 'first(.[] | select(.id == ($id | tonumber)) | .block_time_ms) // empty' "$json_file" 2>/dev/null)
        fi
    fi
    [ -z "$bt" ] && exit 1
    echo "$bt"
    exit 0
fi

# Look up the dRPC lag thresholds (in BLOCKS) for a registry key (slug) or chain id.
# Prints "<lagging_lag> <syncing_lag>". Used by sync-status.sh -> check-health.sh so our
# online/lagging/syncing status matches the dRPC gateway's per-chain lag model.
if [ "$1" = "--lags" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 --lags <slug|chainid>"
        exit 1
    fi
    key="$2"
    lags=$(jq -r --arg k "$key" 'if (.[$k].lagging_lag != null and .[$k].syncing_lag != null) then "\(.[$k].lagging_lag) \(.[$k].syncing_lag)" else empty end' "$json_file" 2>/dev/null)
    if [ -z "$lags" ]; then
        idk="$key"
        [[ "$idk" == 0x* ]] && idk=$(printf "%d" "$idk" 2>/dev/null)
        if [[ "$idk" =~ ^[0-9]+$ ]]; then
            lags=$(jq -r --arg id "$idk" 'first(.[] | select(.id == ($id | tonumber)) | select(.lagging_lag != null and .syncing_lag != null) | "\(.lagging_lag) \(.syncing_lag)") // empty' "$json_file" 2>/dev/null)
        fi
    fi
    [ -z "$lags" ] && exit 1
    echo "$lags"
    exit 0
fi

# Look up by rollup_version (for Aztec: version from result.header.globalVariables.version)
if [ "$1" = "--rollup-version" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 --rollup-version <version_decimal>"
        exit 1
    fi
    version="$2"
    urls=$(jq -r --arg v "$version" '.[] | select(.rollup_version == $v) | .urls[]' "$json_file" 2>/dev/null | tr '\n' ' ')
    if [ -z "$urls" ]; then
        echo "Rollup version not found: $version"
        exit 1
    fi
    echo "$urls"
    exit 0
fi

# Look up by chain id
if [ $# -gt 2 ]; then
    echo "Usage: $0 <chainid> [<index>]"
    exit 1
fi

id="$1"
index="${2:-all}"

# Convert hex id to decimal if necessary
if [[ "$id" == "0x"* ]]; then
    id=$(printf "%d" "$id")
fi

# Find the object with matching id
object=$(jq --arg id "$id" '.[] | select(.id == ($id | tonumber))' "$json_file")

# If object not found, exit
if [ -z "$object" ]; then
    echo "Chain ID not found: $id"
    exit 1
fi

# Extract URLs from the object
urls=$(echo "$object" | jq -r '.urls')

# If index is set to 'all', return all URLs separated by whitespace
if [ "$index" = "all" ]; then
    echo "$urls" | jq -r '.[]' | tr '\n' ' '
    exit
fi

# Otherwise, treat index as numeric
# Validate that index is a number
if ! [[ "$index" =~ ^[0-9]+$ ]]; then
    echo "Invalid index: $index"
    exit 1
fi

# Get the number of URLs
num_urls=$(echo "$urls" | jq -r 'length')

# Check if index is within bounds
if [ "$index" -ge "$num_urls" ]; then
    echo "Index out of bounds: $index (max $(($num_urls - 1)))"
    exit 1
fi

# Get and print the URL at the specified index
url=$(echo "$urls" | jq -r ".[$index]")
echo "$url"
