#!/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)"

# 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 environment variables if .env exists
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
elif [ -f "$PROJECT_ROOT/../.env" ]; then
    source "$PROJECT_ROOT/../.env"
fi

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="0x971cD9D156f193df8051E48043C476e53ECd4693"
WETH10_BRIDGE="0xe0E93247376aa097dB308B92e6Ba36bA015535D0"

# Destination chain configurations
declare -A CHAIN_SELECTORS=(
    ["BSC"]="11344663589394136015"
    ["Polygon"]="4051577828743386545"
    ["Avalanche"]="6433500567565415381"
    ["Base"]="15971525489660198786"
    ["Arbitrum"]="4949039107694359620"
    ["Optimism"]="3734403246176062136"
    ["Ethereum"]="5009297550715157269"
)

declare -A CHAIN_RPC_URLS=(
    ["BSC"]="https://bsc-dataseed.binance.org"
    ["Polygon"]="https://polygon-rpc.com"
    ["Avalanche"]="https://api.avax.network/ext/bc/C/rpc"
    ["Base"]="https://mainnet.base.org"
    ["Arbitrum"]="https://arb1.arbitrum.io/rpc"
    ["Optimism"]="https://mainnet.optimism.io"
    ["Ethereum"]="https://eth.llamarpc.com"
)

declare -A CHAIN_BRIDGE_ADDRESSES_WETH9=(
    ["BSC"]="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
    ["Polygon"]="0xa780ef19a041745d353c9432f2a7f5a241335ffe"
    ["Avalanche"]="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
    ["Base"]="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
    ["Arbitrum"]="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
    ["Optimism"]="0x8078a09637e47fa5ed34f626046ea2094a5cde5e"
    ["Ethereum"]="0x2A0840e5117683b11682ac46f5CF5621E67269E3"
)

declare -A CHAIN_BRIDGE_ADDRESSES_WETH10=(
    ["BSC"]="0x105f8a15b819948a89153505762444ee9f324684"
    ["Polygon"]="0xdab0591e5e89295ffad75a71dcfc30c5625c4fa2"
    ["Avalanche"]="0x105f8a15b819948a89153505762444ee9f324684"
    ["Base"]="0x105f8a15b819948a89153505762444ee9f324684"
    ["Arbitrum"]="0x105f8a15b819948a89153505762444ee9f324684"
    ["Optimism"]="0x105f8a15b819948a89153505762444ee9f324684"
    ["Ethereum"]="0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03"
)

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 "========================================="

