#!/usr/bin/env bash
# Verify Destination Chain Configuration
# Task 15: Create Cross-Chain Verification Script
# Usage: ./verify-destination-chain-config.sh [chain_name]

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=()
declare -A CHAIN_RPC_URLS=()
declare -A CHAIN_BRIDGE_ADDRESSES_WETH9=()
declare -A CHAIN_BRIDGE_ADDRESSES_WETH10=()

while IFS=$'\t' read -r chain_name selector weth9_bridge weth10_bridge rpc_url; do
    CHAIN_SELECTORS["$chain_name"]="$selector"
    CHAIN_RPC_URLS["$chain_name"]="$rpc_url"
    CHAIN_BRIDGE_ADDRESSES_WETH9["$chain_name"]="$weth9_bridge"
    CHAIN_BRIDGE_ADDRESSES_WETH10["$chain_name"]="$weth10_bridge"
done < <(ccip_destination_rows)

CHAIN_NAME="${1:-}"

log_info "========================================="
log_info "Destination Chain Configuration Verification"
log_info "========================================="
log_info ""

if [ -z "$CHAIN_NAME" ]; then
    log_info "Verifying all destination chains..."
    log_info ""
    
    for CHAIN in "${!CHAIN_SELECTORS[@]}"; do
        log_info "--- $CHAIN ---"
        SELECTOR="${CHAIN_SELECTORS[$CHAIN]}"
        
        # Check WETH9 Bridge configuration
        DEST_WETH9=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        DEST_WETH9_CLEAN=$(echo "$DEST_WETH9" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
        
        if [ -n "$DEST_WETH9_CLEAN" ] && ! echo "$DEST_WETH9_CLEAN" | grep -qE "^0x0+$"; then
            EXPECTED="${CHAIN_BRIDGE_ADDRESSES_WETH9[$CHAIN]}"
            if [ "$(echo "$DEST_WETH9_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$EXPECTED" | tr '[:upper:]' '[:lower:]')" ]; then
                log_success "  WETH9 Bridge: $DEST_WETH9_CLEAN (matches expected)"
            else
                log_warn "  WETH9 Bridge: $DEST_WETH9_CLEAN (expected: $EXPECTED)"
            fi
        else
            log_error "  WETH9 Bridge: NOT CONFIGURED"
        fi
        
        # Check WETH10 Bridge configuration
        DEST_WETH10=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        DEST_WETH10_CLEAN=$(echo "$DEST_WETH10" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
        
        if [ -n "$DEST_WETH10_CLEAN" ] && ! echo "$DEST_WETH10_CLEAN" | grep -qE "^0x0+$"; then
            EXPECTED="${CHAIN_BRIDGE_ADDRESSES_WETH10[$CHAIN]}"
            if [ "$(echo "$DEST_WETH10_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$EXPECTED" | tr '[:upper:]' '[:lower:]')" ]; then
                log_success "  WETH10 Bridge: $DEST_WETH10_CLEAN (matches expected)"
            else
                log_warn "  WETH10 Bridge: $DEST_WETH10_CLEAN (expected: $EXPECTED)"
            fi
        else
            log_error "  WETH10 Bridge: NOT CONFIGURED"
        fi
        
        log_info ""
    done
else
    if [ -z "${CHAIN_SELECTORS[$CHAIN_NAME]:-}" ]; then
        log_error "Unknown chain: $CHAIN_NAME"
        log_info "Available chains: ${!CHAIN_SELECTORS[*]}"
        exit 1
    fi
    
    log_info "Verifying $CHAIN_NAME configuration..."
    log_info ""
    
    SELECTOR="${CHAIN_SELECTORS[$CHAIN_NAME]}"
    EXPECTED_WETH9="${CHAIN_BRIDGE_ADDRESSES_WETH9[$CHAIN_NAME]}"
    EXPECTED_WETH10="${CHAIN_BRIDGE_ADDRESSES_WETH10[$CHAIN_NAME]}"
    
    log_info "Chain Selector: $SELECTOR"
    log_info "Expected WETH9 Bridge: $EXPECTED_WETH9"
    log_info "Expected WETH10 Bridge: $EXPECTED_WETH10"
    log_info ""
    
    # Check WETH9 Bridge
    DEST_WETH9=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    DEST_WETH9_CLEAN=$(echo "$DEST_WETH9" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    
    if [ -n "$DEST_WETH9_CLEAN" ] && ! echo "$DEST_WETH9_CLEAN" | grep -qE "^0x0+$"; then
        if [ "$(echo "$DEST_WETH9_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$EXPECTED_WETH9" | tr '[:upper:]' '[:lower:]')" ]; then
            log_success "WETH9 Bridge: $DEST_WETH9_CLEAN (✓ matches expected)"
        else
            log_warn "WETH9 Bridge: $DEST_WETH9_CLEAN (expected: $EXPECTED_WETH9)"
        fi
    else
        log_error "WETH9 Bridge: NOT CONFIGURED"
    fi
    
    # Check WETH10 Bridge
    DEST_WETH10=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    DEST_WETH10_CLEAN=$(echo "$DEST_WETH10" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    
    if [ -n "$DEST_WETH10_CLEAN" ] && ! echo "$DEST_WETH10_CLEAN" | grep -qE "^0x0+$"; then
        if [ "$(echo "$DEST_WETH10_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$EXPECTED_WETH10" | tr '[:upper:]' '[:lower:]')" ]; then
            log_success "WETH10 Bridge: $DEST_WETH10_CLEAN (✓ matches expected)"
        else
            log_warn "WETH10 Bridge: $DEST_WETH10_CLEAN (expected: $EXPECTED_WETH10)"
        fi
    else
        log_error "WETH10 Bridge: NOT CONFIGURED"
    fi
    
    # Try to verify destination chain bridge exists (if RPC available)
    DEST_RPC="${CHAIN_RPC_URLS[$CHAIN_NAME]:-}"
    if [ -n "$DEST_RPC" ]; then
        log_info ""
        log_info "Verifying destination chain bridge contracts..."
        
        if [ -n "$DEST_WETH9_CLEAN" ] && ! echo "$DEST_WETH9_CLEAN" | grep -qE "^0x0+$"; then
            DEST_BYTECODE=$(cast code "$DEST_WETH9_CLEAN" --rpc-url "$DEST_RPC" 2>/dev/null || echo "")
            if [ -n "$DEST_BYTECODE" ] && [ "$DEST_BYTECODE" != "0x" ]; then
                log_success "  WETH9 Bridge on $CHAIN_NAME: Contract exists"
            else
                log_warn "  WETH9 Bridge on $CHAIN_NAME: Contract not found or empty"
            fi
        fi
        
        if [ -n "$DEST_WETH10_CLEAN" ] && ! echo "$DEST_WETH10_CLEAN" | grep -qE "^0x0+$"; then
            DEST_BYTECODE=$(cast code "$DEST_WETH10_CLEAN" --rpc-url "$DEST_RPC" 2>/dev/null || echo "")
            if [ -n "$DEST_BYTECODE" ] && [ "$DEST_BYTECODE" != "0x" ]; then
                log_success "  WETH10 Bridge on $CHAIN_NAME: Contract exists"
            else
                log_warn "  WETH10 Bridge on $CHAIN_NAME: Contract not found or empty"
            fi
        fi
    fi
fi

log_info ""
log_info "========================================="
log_info "Verification Complete"
log_info "========================================="
