#!/usr/bin/env bash
# Verify CCIP deployment on ChainID 138

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Load environment
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

RPC_URL="${RPC_URL_138:-${CHAIN138_RPC_URL:-http://localhost:8545}}"

log_info "=== CCIP Deployment Verification for ChainID 138 ==="
echo "RPC URL: $RPC_URL"
echo ""

# Check if RPC is accessible
if ! cast block-number --rpc-url "$RPC_URL" &>/dev/null; then
    log_error "Error: Cannot connect to RPC at $RPC_URL"
    exit 1
fi

CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "unknown")
if [ "$CHAIN_ID" != "138" ]; then
    log_warn "⚠️  Warning: Chain ID is $CHAIN_ID, expected 138"
fi

echo "Chain ID: $CHAIN_ID"
echo ""

# Required addresses
CCIP_ROUTER="${CCIP_CHAIN138_ROUTER:-}"
LINK_TOKEN="${CCIP_CHAIN138_LINK_TOKEN:-}"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-}"
CHAIN_SELECTOR="${CHAIN138_SELECTOR:-}"

# Verification results
VERIFICATION_PASSED=0
VERIFICATION_FAILED=0
VERIFICATION_WARNINGS=0

check_contract() {
    local name=$1
    local address=$2
    local required=${3:-true}
    
    if [ -z "$address" ] || [ "$address" = "" ]; then
        if [ "$required" = "true" ]; then
            echo "  ❌ $name: Not configured"
            ((VERIFICATION_FAILED++))
        else
            echo "  ⚠️  $name: Not configured (optional)"
            ((VERIFICATION_WARNINGS++))
        fi
        return 1
    fi
    
    # Check if address has code
    CODE=$(cast code "$address" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -z "$CODE" ] || [ "$CODE" = "0x" ]; then
        echo "  ❌ $name: No code at address $address"
        ((VERIFICATION_FAILED++))
        return 1
    fi
    
    echo "  ✅ $name: Deployed at $address"
    ((VERIFICATION_PASSED++))
    return 0
}

verify_router_config() {
    local router=$1
    if [ -z "$router" ]; then
        return 1
    fi
    
    echo ""
    echo "Router Configuration:"
    
    # Check supported chains
    ETH_SELECTOR="5009297550715157269"
    ETH_SUPPORTED=$(cast call "$router" "supportedChains(uint64)" "$ETH_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "false")
    if [ "$ETH_SUPPORTED" = "true" ]; then
        echo "  ✅ Ethereum Mainnet is supported"
    else
        echo "  ⚠️  Ethereum Mainnet not configured as supported chain"
        ((VERIFICATION_WARNINGS++))
    fi
    
    # Check fee token
    FEE_TOKEN=$(cast call "$router" "feeToken()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$FEE_TOKEN" ]; then
        if [ "$FEE_TOKEN" = "0x0000000000000000000000000000000000000000" ]; then
            echo "  ✅ Fee token: Native ETH"
        else
            echo "  ✅ Fee token: $FEE_TOKEN"
        fi
    fi
}

verify_bridge_config() {
    local bridge=$1
    local name=$2
    if [ -z "$bridge" ]; then
        return 1
    fi
    
    echo ""
    echo "$name Configuration:"
    
    # Check router
    BRIDGE_ROUTER=$(cast call "$bridge" "ccipRouter()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$BRIDGE_ROUTER" ] && [ "$BRIDGE_ROUTER" != "0x0000000000000000000000000000000000000000" ]; then
        echo "  ✅ Router: $BRIDGE_ROUTER"
    else
        echo "  ⚠️  Router not configured"
        ((VERIFICATION_WARNINGS++))
    fi
    
    # Check destinations
    ETH_SELECTOR="5009297550715157269"
    DEST=$(cast call "$bridge" "destinations(uint64)" "$ETH_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$DEST" ] && echo "$DEST" | grep -q "0x[0-9a-f]\{40\}"; then
        echo "  ✅ Ethereum Mainnet destination configured"
    else
        echo "  ⚠️  Ethereum Mainnet destination not configured"
        ((VERIFICATION_WARNINGS++))
    fi
}

echo "=== Contract Deployment Verification ==="
check_contract "CCIP Router" "$CCIP_ROUTER" true
check_contract "LINK Token" "$LINK_TOKEN" false
check_contract "CCIPWETH9Bridge" "$WETH9_BRIDGE" true
check_contract "CCIPWETH10Bridge" "$WETH10_BRIDGE" true

if [ -n "$CCIP_ROUTER" ]; then
    verify_router_config "$CCIP_ROUTER"
fi

if [ -n "$WETH9_BRIDGE" ]; then
    verify_bridge_config "$WETH9_BRIDGE" "CCIPWETH9Bridge"
fi

if [ -n "$WETH10_BRIDGE" ]; then
    verify_bridge_config "$WETH10_BRIDGE" "CCIPWETH10Bridge"
fi

echo ""
echo "=== Chain Selector ==="
if [ -n "$CHAIN_SELECTOR" ]; then
    echo "  ✅ Chain Selector: $CHAIN_SELECTOR"
else
    echo "  ⚠️  Chain Selector: Not configured"
    ((VERIFICATION_WARNINGS++))
fi

echo ""
echo "=== Verification Summary ==="
echo "✅ Passed: $VERIFICATION_PASSED"
echo "❌ Failed: $VERIFICATION_FAILED"
echo "⚠️  Warnings: $VERIFICATION_WARNINGS"
echo ""

if [ $VERIFICATION_FAILED -eq 0 ]; then
    log_success "✅ All required contracts are deployed!"
    if [ $VERIFICATION_WARNINGS -gt 0 ]; then
        log_warn "⚠️  Some optional configurations are missing"
    fi
    exit 0
else
    log_error "❌ Some required contracts are missing or invalid"
    exit 1
fi

