#!/usr/bin/env bash
# Comprehensive Chain-138 deployment verification

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR/../.."
[ -f "$SCRIPT_DIR/../lib/init.sh" ] && source "$SCRIPT_DIR/../lib/init.sh" 2>/dev/null || true

# Color codes (fallbacks if init.sh not loaded)
: "${GREEN:=\033[0;32m}"
: "${RED:=\033[0;31m}"
: "${YELLOW:=\033[1;33m}"
: "${NC:=\033[0m}"
log_info() { echo "$@"; }
log_success() { echo "$@"; }
log_warn() { echo "$@"; }
log_error() { echo "$@" >&2; }

echo "==================================================================="
echo "  CHAIN-138 FULL DEPLOYMENT VERIFICATION"
echo "==================================================================="

# Load environment variables
if [ -f .env ]; then
    set +u
    source .env 2>/dev/null || true
    set -u 2>/dev/null || true
fi

# Optional vars (allow unset for graceful checks)
CHAIN138_CCIP_REPORTER="${CHAIN138_CCIP_REPORTER:-}"
CCIP_CHAIN138_ROUTER="${CCIP_CHAIN138_ROUTER:-$CCIP_ROUTER}"
CHAIN138_CCIP_WETH9_BRIDGE="${CHAIN138_CCIP_WETH9_BRIDGE:-$CCIPWETH9_BRIDGE_CHAIN138}"
CHAIN138_CCIP_WETH10_BRIDGE="${CHAIN138_CCIP_WETH10_BRIDGE:-$CCIPWETH10_BRIDGE_CHAIN138}"

ERRORS=0
WARNINGS=0
SUCCESS=0

# Function to check status
check_status() {
    local name=$1
    local status=$2
    local details=$3
    
    if [ "$status" = "success" ]; then
        echo -e "  ${GREEN}✅ $name${NC}"
        SUCCESS=$((SUCCESS + 1))
    elif [ "$status" = "warning" ]; then
        echo -e "  ${YELLOW}⚠️  $name${NC}"
        WARNINGS=$((WARNINGS + 1))
    else
        echo -e "  ${RED}❌ $name${NC}"
        ERRORS=$((ERRORS + 1))
    fi
    
    if [ -n "$details" ]; then
        echo "    $details"
    fi
}

log_info "1. Infrastructure Verification"

# Check RPC endpoint
if [ -n "$CHAIN138_RPC_URL" ] && [ "$CHAIN138_RPC_URL" != "" ]; then
    echo -n "  Checking RPC endpoint: "
    if curl -s --max-time 5 "$CHAIN138_RPC_URL" -X POST -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null | grep -q "result"; then
        check_status "RPC Endpoint" "success" "$CHAIN138_RPC_URL"
    else
        check_status "RPC Endpoint" "error" "$CHAIN138_RPC_URL (not accessible)"
    fi
else
    check_status "RPC Endpoint" "error" "Not configured in .env"
fi

# Check chain ID
if [ -n "$CHAIN138_RPC_URL" ]; then
    echo -n "  Checking Chain ID: "
    CHAIN_ID=$(curl -s --max-time 5 "$CHAIN138_RPC_URL" -X POST -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>/dev/null | \
        python3 -c "import sys, json; print(int(json.load(sys.stdin).get('result', '0x0'), 16))" 2>/dev/null || echo "0")
    if [ "$CHAIN_ID" = "138" ]; then
        check_status "Chain ID" "success" "Chain ID: 138 (correct)"
    else
        check_status "Chain ID" "warning" "Chain ID: $CHAIN_ID (expected 138)"
    fi
else
    check_status "Chain ID" "error" "Cannot check (RPC not configured)"
fi

# Check latest block
if [ -n "$CHAIN138_RPC_URL" ]; then
    echo -n "  Checking Latest Block: "
    BLOCK_NUM=$(curl -s --max-time 5 "$CHAIN138_RPC_URL" -X POST -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null | \
        python3 -c "import sys, json; print(int(json.load(sys.stdin).get('result', '0x0'), 16))" 2>/dev/null || echo "0")
    if [ "$BLOCK_NUM" -gt 0 ]; then
        check_status "Latest Block" "success" "Block: $BLOCK_NUM"
    else
        check_status "Latest Block" "error" "Cannot retrieve block number"
    fi
else
    check_status "Latest Block" "error" "Cannot check (RPC not configured)"
fi

log_info "2. Predeployed Contracts Verification"

# WETH9 on Chain-138
WETH9_ADDR="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
    echo -n "  Checking WETH9: "
    WETH9_CODE=$(cast code "$WETH9_ADDR" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
    if [ -n "$WETH9_CODE" ] && [ "$WETH9_CODE" != "0x" ] && [ ${#WETH9_CODE} -gt 2 ]; then
        check_status "WETH9" "success" "$WETH9_ADDR"
    else
        check_status "WETH9" "error" "$WETH9_ADDR (no code found)"
    fi
else
    check_status "WETH9" "warning" "$WETH9_ADDR (cannot verify - RPC or cast not available)"
fi

# WETH10 on Chain-138
WETH10_ADDR="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
    echo -n "  Checking WETH10: "
    WETH10_CODE=$(cast code "$WETH10_ADDR" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
    if [ -n "$WETH10_CODE" ] && [ "$WETH10_CODE" != "0x" ] && [ ${#WETH10_CODE} -gt 2 ]; then
        check_status "WETH10" "success" "$WETH10_ADDR"
    else
        check_status "WETH10" "error" "$WETH10_ADDR (no code found)"
    fi
else
    check_status "WETH10" "warning" "$WETH10_ADDR (cannot verify - RPC or cast not available)"
fi

log_info "3. CCIP Integration Contracts"

# CCIPTxReporter
if [ -n "$CHAIN138_CCIP_REPORTER" ] && [ "$CHAIN138_CCIP_REPORTER" != "" ]; then
    if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
        echo -n "  Checking CCIPTxReporter: "
        REPORTER_CODE=$(cast code "$CHAIN138_CCIP_REPORTER" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$REPORTER_CODE" ] && [ "$REPORTER_CODE" != "0x" ] && [ ${#REPORTER_CODE} -gt 2 ]; then
            check_status "CCIPTxReporter" "success" "$CHAIN138_CCIP_REPORTER"
        else
            check_status "CCIPTxReporter" "error" "$CHAIN138_CCIP_REPORTER (address in .env but no code on-chain)"
        fi
    else
        check_status "CCIPTxReporter" "warning" "$CHAIN138_CCIP_REPORTER (address in .env, cannot verify on-chain)"
    fi
else
    check_status "CCIPTxReporter" "warning" "Not deployed (optional; set CHAIN138_CCIP_REPORTER when deployed)"
fi

# CCIP Router on Chain-138
if [ -n "$CCIP_CHAIN138_ROUTER" ] && [ "$CCIP_CHAIN138_ROUTER" != "" ]; then
    if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
        echo -n "  Checking CCIP Router: "
        ROUTER_CODE=$(cast code "$CCIP_CHAIN138_ROUTER" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$ROUTER_CODE" ] && [ "$ROUTER_CODE" != "0x" ] && [ ${#ROUTER_CODE} -gt 2 ]; then
            check_status "CCIP Router" "success" "$CCIP_CHAIN138_ROUTER"
        else
            check_status "CCIP Router" "error" "$CCIP_CHAIN138_ROUTER (address in .env but no code on-chain)"
        fi
    else
        check_status "CCIP Router" "warning" "$CCIP_CHAIN138_ROUTER (address in .env, cannot verify on-chain)"
    fi
else
    check_status "CCIP Router" "warning" "Not configured in .env (may use official Chainlink router)"
fi

log_info "4. Bridge Contracts on Chain-138"

# Check for bridge contracts on Chain-138
if [ -n "$CHAIN138_CCIP_WETH9_BRIDGE" ] && [ "$CHAIN138_CCIP_WETH9_BRIDGE" != "" ]; then
    if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
        echo -n "  Checking CCIPWETH9Bridge: "
        BRIDGE9_CODE=$(cast code "$CHAIN138_CCIP_WETH9_BRIDGE" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$BRIDGE9_CODE" ] && [ "$BRIDGE9_CODE" != "0x" ] && [ ${#BRIDGE9_CODE} -gt 2 ]; then
            check_status "CCIPWETH9Bridge" "success" "$CHAIN138_CCIP_WETH9_BRIDGE"
        else
            check_status "CCIPWETH9Bridge" "error" "$CHAIN138_CCIP_WETH9_BRIDGE (address in .env but no code on-chain)"
        fi
    else
        check_status "CCIPWETH9Bridge" "warning" "$CHAIN138_CCIP_WETH9_BRIDGE (address in .env, cannot verify on-chain)"
    fi
else
    check_status "CCIPWETH9Bridge" "warning" "Not configured (may not be needed on Chain-138)"
fi

if [ -n "$CHAIN138_CCIP_WETH10_BRIDGE" ] && [ "$CHAIN138_CCIP_WETH10_BRIDGE" != "" ]; then
    if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
        echo -n "  Checking CCIPWETH10Bridge: "
        BRIDGE10_CODE=$(cast code "$CHAIN138_CCIP_WETH10_BRIDGE" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$BRIDGE10_CODE" ] && [ "$BRIDGE10_CODE" != "0x" ] && [ ${#BRIDGE10_CODE} -gt 2 ]; then
            check_status "CCIPWETH10Bridge" "success" "$CHAIN138_CCIP_WETH10_BRIDGE"
        else
            check_status "CCIPWETH10Bridge" "error" "$CHAIN138_CCIP_WETH10_BRIDGE (address in .env but no code on-chain)"
        fi
    else
        check_status "CCIPWETH10Bridge" "warning" "$CHAIN138_CCIP_WETH10_BRIDGE (address in .env, cannot verify on-chain)"
    fi
else
    check_status "CCIPWETH10Bridge" "warning" "Not configured (may not be needed on Chain-138)"
fi

log_info "5. Kubernetes Services (if applicable)"

# Check if kubectl is available and configured
if command -v kubectl &> /dev/null; then
    echo -n "  Checking Kubernetes access: "
    if kubectl cluster-info &> /dev/null; then
        check_status "Kubernetes" "success" "Cluster accessible"
        
        # Check for Chain-138 namespace
        if kubectl get namespace besu-network &> /dev/null; then
            check_status "Namespace (besu-network)" "success" "Exists"
            
            # Check for pods
            POD_COUNT=$(kubectl get pods -n besu-network 2>/dev/null | grep -v NAME | wc -l)
            if [ "$POD_COUNT" -gt 0 ]; then
                check_status "Pods" "success" "$POD_COUNT pods running"
            else
                check_status "Pods" "warning" "No pods found"
            fi
        else
            check_status "Namespace (besu-network)" "warning" "Not found"
        fi
    else
        check_status "Kubernetes" "warning" "Cannot access cluster"
    fi
else
    check_status "Kubernetes" "warning" "kubectl not available"
fi

log_info "6. Configuration Files"

# Check genesis file
if [ -f "genesis.json" ]; then
    check_status "Genesis File" "success" "genesis.json exists"
    
    # Check if WETH9/WETH10 are in alloc
    if grep -q "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" genesis.json 2>/dev/null; then
        check_status "WETH9 in Genesis" "success" "Predeployed in alloc"
    else
        check_status "WETH9 in Genesis" "warning" "Not found in genesis.json"
    fi
    
    if grep -q "f4BB2e28688e89fCcE3c0580D37d36A7672E8A9f" genesis.json 2>/dev/null; then
        check_status "WETH10 in Genesis" "success" "Predeployed in alloc"
    else
        check_status "WETH10 in Genesis" "warning" "Not found in genesis.json"
    fi
else
    check_status "Genesis File" "warning" "genesis.json not found (optional for RPC-only Chain 138)"
fi

# Check .env configuration
if [ -f .env ]; then
    check_status ".env File" "success" "Exists"
    
    # Check required variables
    REQUIRED_VARS=("CHAIN138_RPC_URL" "CHAIN138_SELECTOR")
    for var in "${REQUIRED_VARS[@]}"; do
        if grep -q "^${var}=" .env 2>/dev/null; then
            check_status "$var" "success" "Configured"
        else
            check_status "$var" "warning" "Not configured"
        fi
    done
else
    check_status ".env File" "error" "Not found"
fi

log_info "7. Network Connectivity"

# Test RPC connectivity
if [ -n "$CHAIN138_RPC_URL" ]; then
    echo -n "  Testing RPC connectivity: "
    RESPONSE_TIME=$(curl -o /dev/null -s -w '%{time_total}' --max-time 5 "$CHAIN138_RPC_URL" -X POST -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null || echo "999")
    if (( $(echo "$RESPONSE_TIME < 5.0" | bc -l 2>/dev/null || echo "0") )); then
        check_status "RPC Connectivity" "success" "Response time: ${RESPONSE_TIME}s"
    else
        check_status "RPC Connectivity" "error" "Timeout or unreachable"
    fi
else
    check_status "RPC Connectivity" "error" "RPC URL not configured"
fi

echo "==================================================================="
log_info "SUMMARY"
echo "==================================================================="
echo "  ✅ Successful: $SUCCESS"
echo "  ⚠️  Warnings: $WARNINGS"
echo "  ❌ Errors: $ERRORS"

if [ $ERRORS -eq 0 ] && [ $WARNINGS -eq 0 ]; then
    log_success "✅ Chain-138 is fully deployed and verified!"
    exit 0
elif [ $ERRORS -eq 0 ]; then
    log_warn "⚠️  Chain-138 is deployed with some warnings"
    exit 0
else
    log_error "❌ Chain-138 deployment has errors that need to be addressed"
    exit 1
fi
