#!/usr/bin/env bash
# Comprehensive CCIP Setup Verification
# Task 139: Create Comprehensive CCIP Verification Script
# Usage: ./verify-complete-ccip-setup.sh

set -euo pipefail

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

# Counters
TOTAL_CHECKS=0
PASSED_CHECKS=0
FAILED_CHECKS=0
WARNING_CHECKS=0

check_pass() {
    ((TOTAL_CHECKS++)) || true
    ((PASSED_CHECKS++)) || true
    log_success "$1"
}

check_fail() {
    ((TOTAL_CHECKS++)) || true
    ((FAILED_CHECKS++)) || true
    log_error "$1"
}

check_warn() {
    ((TOTAL_CHECKS++)) || true
    ((WARNING_CHECKS++)) || true
    log_warn "$1"
}

log_info "========================================="
log_info "Comprehensive CCIP Setup Verification"
log_info "========================================="
log_info ""
log_info "RPC URL: $RPC_URL"
log_info "Date: $(date)"
log_info ""

# Section A: CCIP Lane Configuration
log_info "========================================="
log_info "A) CCIP Lane Configuration"
log_info "========================================="
log_info ""

# A.1: Router Deployment
log_info "A.1: Router Deployment"
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_pass "Router contract deployed: $ROUTER"
else
    check_fail "Router contract not found: $ROUTER"
fi

# A.2: Sender Deployment
log_info ""
log_info "A.2: Sender Deployment"
SENDER="0x105F8A15b819948a89153505762444Ee9f324684"
SENDER_BYTECODE=$(cast code "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$SENDER_BYTECODE" ] && [ "$SENDER_BYTECODE" != "0x" ]; then
    check_pass "Sender contract deployed: $SENDER"
else
    check_fail "Sender contract not found: $SENDER"
fi

# A.3: Bridge Destinations
log_info ""
log_info "A.3: Bridge Destination Configuration"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

WETH9_CONFIGURED=0
WETH10_CONFIGURED=0
TOTAL_DESTINATIONS=$(ccip_destination_count)

while IFS=$'\t' read -r _chain_name SELECTOR _weth9 _weth10 _rpc_url; do
    
    # Check WETH9
    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
    
    # Check WETH10
    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_pass "WETH9 Bridge: All $TOTAL_DESTINATIONS destinations configured"
elif [ $WETH9_CONFIGURED -gt 0 ]; then
    check_warn "WETH9 Bridge: $WETH9_CONFIGURED/$TOTAL_DESTINATIONS destinations configured"
else
    check_fail "WETH9 Bridge: No destinations configured"
fi

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

# Section B: Token Configuration
log_info ""
log_info "========================================="
log_info "B) Token Configuration"
log_info "========================================="
log_info ""

# B.1: WETH9 Token
log_info "B.1: WETH9 Token"
WETH9="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH9_BYTECODE=$(cast code "$WETH9" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$WETH9_BYTECODE" ] && [ "$WETH9_BYTECODE" != "0x" ]; then
    check_pass "WETH9 token deployed: $WETH9"
    
    # Check 1:1 ratio
    WETH9_BALANCE=$(cast balance "$WETH9" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH9_SUPPLY=$(cast call "$WETH9" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$WETH9_BALANCE" = "$WETH9_SUPPLY" ]; then
        check_pass "WETH9 1:1 ratio verified"
    else
        check_warn "WETH9 1:1 ratio: Balance=$WETH9_BALANCE, Supply=$WETH9_SUPPLY"
    fi
else
    check_fail "WETH9 token not found: $WETH9"
fi

# B.2: WETH10 Token
log_info ""
log_info "B.2: WETH10 Token"
WETH10="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
WETH10_BYTECODE=$(cast code "$WETH10" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$WETH10_BYTECODE" ] && [ "$WETH10_BYTECODE" != "0x" ]; then
    check_pass "WETH10 token deployed: $WETH10"
    
    # Check 1:1 ratio
    WETH10_BALANCE=$(cast balance "$WETH10" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH10_SUPPLY=$(cast call "$WETH10" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$WETH10_BALANCE" = "$WETH10_SUPPLY" ]; then
        check_pass "WETH10 1:1 ratio verified"
    else
        check_warn "WETH10 1:1 ratio: Balance=$WETH10_BALANCE, Supply=$WETH10_SUPPLY"
    fi
else
    check_fail "WETH10 token not found: $WETH10"
fi

# Section C: Bridge Contracts
log_info ""
log_info "========================================="
log_info "C) Bridge Contracts"
log_info "========================================="
log_info ""

# C.1: WETH9 Bridge
log_info "C.1: WETH9 Bridge"
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_pass "WETH9 Bridge deployed: $WETH9_BRIDGE"
else
    check_fail "WETH9 Bridge not found: $WETH9_BRIDGE"
fi

# C.2: WETH10 Bridge
log_info ""
log_info "C.2: WETH10 Bridge"
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_pass "WETH10 Bridge deployed: $WETH10_BRIDGE"
else
    check_fail "WETH10 Bridge not found: $WETH10_BRIDGE"
fi

# Section D: Fee Configuration
log_info ""
log_info "========================================="
log_info "D) Fee Configuration"
log_info "========================================="
log_info ""

# D.1: Fee Token
log_info "D.1: Fee Token Configuration"
FEE_TOKEN=$(cast call "$ROUTER" "getFeeToken()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$FEE_TOKEN" ] && [ "$FEE_TOKEN" != "0x" ]; then
    FEE_TOKEN_CLEAN=$(echo "$FEE_TOKEN" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    if [ -n "$FEE_TOKEN_CLEAN" ]; then
        check_pass "Fee token configured: $FEE_TOKEN_CLEAN"
    else
        check_warn "Fee token returned invalid address"
    fi
else
    check_warn "Fee token configuration not accessible"
fi

# D.2: Fee Calculation
log_info ""
log_info "D.2: Fee Calculation"
ETHEREUM_SELECTOR="${ETHEREUM_SELECTOR:-$(ccip_destination_selector_by_name "Ethereum Mainnet")}"
FEE_RESULT=$(cast call "$ROUTER" "getFee(uint64,bytes)" "$ETHEREUM_SELECTOR" "0x" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$FEE_RESULT" ] && [ "$FEE_RESULT" != "0x" ]; then
    check_pass "Fee calculation accessible"
else
    check_warn "Fee calculation not accessible"
fi

# Summary
log_info ""
log_info "========================================="
log_info "Verification Summary"
log_info "========================================="
log_info ""
log_info "Total Checks: $TOTAL_CHECKS"
log_success "Passed: $PASSED_CHECKS"
log_warn "Warnings: $WARNING_CHECKS"
log_error "Failed: $FAILED_CHECKS"
log_info ""

if [ $FAILED_CHECKS -eq 0 ]; then
    if [ $WARNING_CHECKS -eq 0 ]; then
        log_success "✓ All checks passed!"
        exit 0
    else
        log_warn "⚠ Some checks have warnings"
        exit 0
    fi
else
    log_error "✗ Some checks failed"
    exit 1
fi
