#!/usr/bin/env bash
# CCIP Health Check
# Task 140: Create CCIP Health Check Script
# Usage: ./ccip-health-check.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}"

HEALTHY=0
UNHEALTHY=0
WARNINGS=0

check_healthy() {
    ((HEALTHY++)) || true
    log_success "$1"
}

check_unhealthy() {
    ((UNHEALTHY++)) || true
    log_error "$1"
}

check_warning() {
    ((WARNINGS++)) || true
    log_warn "$1"
}

log_info "========================================="
log_info "CCIP Health Check"
log_info "========================================="
log_info ""
log_info "RPC URL: $RPC_URL"
log_info "Date: $(date)"
log_info ""

# Check RPC connectivity
log_info "1. RPC Connectivity"
BLOCK_NUMBER=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$BLOCK_NUMBER" ]; then
    check_healthy "RPC accessible (block: $BLOCK_NUMBER)"
else
    check_unhealthy "RPC not accessible"
    exit 1
fi

# Check Router
log_info ""
log_info "2. CCIP Router"
ROUTER="$(resolve_address_value CCIP_ROUTER_ADDRESS CCIP_ROUTER_ADDRESS 0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817)"
ROUTER_BYTECODE=$(cast code "$ROUTER" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$ROUTER_BYTECODE" ] && [ "$ROUTER_BYTECODE" != "0x" ]; then
    check_healthy "Router deployed and accessible"
else
    check_unhealthy "Router not found"
fi

# Check Sender
log_info ""
log_info "3. CCIP Sender"
SENDER="0x105F8A15b819948a89153505762444Ee9f324684"
SENDER_BYTECODE=$(cast code "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$SENDER_BYTECODE" ] && [ "$SENDER_BYTECODE" != "0x" ]; then
    check_healthy "Sender deployed and accessible"
else
    check_unhealthy "Sender not found"
fi

# Check Bridge Contracts
log_info ""
log_info "4. Bridge Contracts"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

WETH9_BRIDGE_BYTECODE=$(cast code "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$WETH9_BRIDGE_BYTECODE" ] && [ "$WETH9_BRIDGE_BYTECODE" != "0x" ]; then
    check_healthy "WETH9 Bridge deployed"
else
    check_unhealthy "WETH9 Bridge not found"
fi

WETH10_BRIDGE_BYTECODE=$(cast code "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$WETH10_BRIDGE_BYTECODE" ] && [ "$WETH10_BRIDGE_BYTECODE" != "0x" ]; then
    check_healthy "WETH10 Bridge deployed"
else
    check_unhealthy "WETH10 Bridge not found"
fi

# Check Token Contracts
log_info ""
log_info "5. Token Contracts"
WETH9="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"

WETH9_BYTECODE=$(cast code "$WETH9" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$WETH9_BYTECODE" ] && [ "$WETH9_BYTECODE" != "0x" ]; then
    check_healthy "WETH9 token deployed"
else
    check_unhealthy "WETH9 token not found"
fi

WETH10_BYTECODE=$(cast code "$WETH10" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$WETH10_BYTECODE" ] && [ "$WETH10_BYTECODE" != "0x" ]; then
    check_healthy "WETH10 token deployed"
else
    check_unhealthy "WETH10 token not found"
fi

# Check Bridge Configuration
log_info ""
log_info "6. Bridge Configuration"
WETH9_CONFIGURED=0
WETH10_CONFIGURED=0
TOTAL_DESTINATIONS=$(ccip_destination_count)

while IFS=$'\t' read -r _chain_name SELECTOR _weth9 _weth10 _rpc_url; do
    
    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
        ((WETH9_CONFIGURED++)) || true
    fi
    
    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
        ((WETH10_CONFIGURED++)) || true
    fi
done < <(ccip_destination_rows)

if [ $WETH9_CONFIGURED -eq $TOTAL_DESTINATIONS ]; then
    check_healthy "WETH9 Bridge: All destinations configured"
elif [ $WETH9_CONFIGURED -gt 0 ]; then
    check_warning "WETH9 Bridge: $WETH9_CONFIGURED/$TOTAL_DESTINATIONS destinations configured"
else
    check_unhealthy "WETH9 Bridge: No destinations configured"
fi

if [ $WETH10_CONFIGURED -eq $TOTAL_DESTINATIONS ]; then
    check_healthy "WETH10 Bridge: All destinations configured"
elif [ $WETH10_CONFIGURED -gt 0 ]; then
    check_warning "WETH10 Bridge: $WETH10_CONFIGURED/$TOTAL_DESTINATIONS destinations configured"
else
    check_unhealthy "WETH10 Bridge: No destinations configured"
fi

# Summary
log_info ""
log_info "========================================="
log_info "Health Check Summary"
log_info "========================================="
log_info ""
log_success "Healthy: $HEALTHY"
log_warn "Warnings: $WARNINGS"
log_error "Unhealthy: $UNHEALTHY"
log_info ""

if [ $UNHEALTHY -eq 0 ]; then
    if [ $WARNINGS -eq 0 ]; then
        log_success "✓ System is healthy"
        exit 0
    else
        log_warn "⚠ System is healthy with warnings"
        exit 0
    fi
else
    log_error "✗ System has health issues"
    exit 1
fi
