#!/usr/bin/env bash
# Check bridge configuration for all destinations
# Shows what's configured and what's missing
# Usage: ./check-bridge-config.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"
source "$PROJECT_ROOT/scripts/lib/ccip-destinations.sh"

# Colors
RED='\033[0;31m'
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"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

load_explorer_runtime_env

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

declare -A CHAIN_SELECTORS=()
while IFS=$'\t' read -r chain_name selector _weth9 _weth10 _rpc_url; do
    CHAIN_SELECTORS["$chain_name"]="$selector"
done < <(ccip_destination_rows)

log_info "========================================="
log_info "Bridge Configuration Check"
log_info "========================================="
log_info ""
log_info "WETH9 Bridge: $WETH9_BRIDGE"
log_info "WETH10 Bridge: $WETH10_BRIDGE"
log_info "RPC URL: $RPC_URL"
log_info ""

# Check WETH9 Bridge
log_info "WETH9 Bridge Destinations:"
log_info ""

CONFIGURED_COUNT=0
MISSING_COUNT=0

for CHAIN_NAME in "${!CHAIN_SELECTORS[@]}"; do
    SELECTOR="${CHAIN_SELECTORS[$CHAIN_NAME]}"
    DEST=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    
    # destinations() returns a tuple: (uint64, address, bool)
    # Extract the address (second element, starts at position 64 in hex string)
    # Remove 0x prefix, get 64-char chunk starting at position 64 (address is padded to 64 chars)
    DEST_HEX=$(echo "$DEST" | sed 's/0x//')
    if [ ${#DEST_HEX} -ge 128 ]; then
        # Address is the second 64-char chunk (positions 64-127)
        ADDR_HEX=$(echo "$DEST_HEX" | cut -c65-128)
        DEST_CLEAN="0x${ADDR_HEX:24:40}"  # Address is right-aligned in the 64-char chunk
    else
        DEST_CLEAN=""
    fi
    
    # Check if result is valid address (not zero or empty)
    if [ -n "$DEST_CLEAN" ] && ! echo "$DEST_CLEAN" | grep -qE "^0x0+$" && [ "$DEST_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
        log_success "  $CHAIN_NAME ($SELECTOR): $DEST_CLEAN"
        ((CONFIGURED_COUNT++)) || true
    else
        log_error "  $CHAIN_NAME ($SELECTOR): NOT CONFIGURED"
        ((MISSING_COUNT++)) || true
    fi
done

log_info ""
log_info "WETH9 Summary: $CONFIGURED_COUNT configured, $MISSING_COUNT missing"
log_info ""

# Check WETH10 Bridge
log_info "WETH10 Bridge Destinations:"
log_info ""

CONFIGURED_COUNT_10=0
MISSING_COUNT_10=0

for CHAIN_NAME in "${!CHAIN_SELECTORS[@]}"; do
    SELECTOR="${CHAIN_SELECTORS[$CHAIN_NAME]}"
    DEST=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    
    # destinations() returns a tuple: (uint64, address, bool)
    # Extract the address (second element, starts at position 64 in hex string)
    # Remove 0x prefix, get 64-char chunk starting at position 64 (address is padded to 64 chars)
    DEST_HEX=$(echo "$DEST" | sed 's/0x//')
    if [ ${#DEST_HEX} -ge 128 ]; then
        # Address is the second 64-char chunk (positions 64-127)
        ADDR_HEX=$(echo "$DEST_HEX" | cut -c65-128)
        DEST_CLEAN="0x${ADDR_HEX:24:40}"  # Address is right-aligned in the 64-char chunk
    else
        DEST_CLEAN=""
    fi
    
    # Check if result is valid address (not zero or empty)
    if [ -n "$DEST_CLEAN" ] && ! echo "$DEST_CLEAN" | grep -qE "^0x0+$" && [ "$DEST_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
        log_success "  $CHAIN_NAME ($SELECTOR): $DEST_CLEAN"
        ((CONFIGURED_COUNT_10++)) || true
    else
        log_error "  $CHAIN_NAME ($SELECTOR): NOT CONFIGURED"
        ((MISSING_COUNT_10++)) || true
    fi
done

log_info ""
log_info "WETH10 Summary: $CONFIGURED_COUNT_10 configured, $MISSING_COUNT_10 missing"
log_info ""

# Summary
log_info "========================================="
log_info "Summary"
log_info "========================================="
log_info ""

if [ $MISSING_COUNT -eq 0 ]; then
    log_success "✓ WETH9 Bridge: All destinations configured"
else
    log_warn "⚠ WETH9 Bridge: $MISSING_COUNT destination(s) missing"
    if [ $MISSING_COUNT -eq 1 ] && [ -n "${CHAIN_SELECTORS[Ethereum]:-}" ]; then
        log_info "  Missing: Ethereum Mainnet"
        log_info "  Fix: ./scripts/fix-bridge-errors.sh [private_key] [ethereum_mainnet_bridge_address]"
    fi
fi

if [ $MISSING_COUNT_10 -eq 0 ]; then
    log_success "✓ WETH10 Bridge: All destinations configured"
else
    log_warn "⚠ WETH10 Bridge: $MISSING_COUNT_10 destination(s) missing"
fi

log_info ""
