#!/usr/bin/env bash

# Validate Deployment
# This script validates that all deployments are working correctly

set -e

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


log_success "Validating Deployment..."

# Check namespace
log_warn "Checking namespace..."
if kubectl get namespace "$NAMESPACE" &>/dev/null; then
    log_success "✓ Namespace $NAMESPACE exists"
else
    log_warn "⚠ Namespace $NAMESPACE not found, creating..."
    kubectl create namespace "$NAMESPACE"
fi

# Check validators
log_warn "Checking validators..."
VALIDATOR_STS=$(kubectl get statefulset besu-validator -n "$NAMESPACE" -o name 2>/dev/null || echo "")
if [ -n "$VALIDATOR_STS" ]; then
    log_success "✓ Validator StatefulSet exists"
    
    # Check replica count
    DESIRED=$(kubectl get statefulset besu-validator -n "$NAMESPACE" -o jsonpath='{.spec.replicas}' 2>/dev/null || echo "0")
    READY=$(kubectl get statefulset besu-validator -n "$NAMESPACE" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || echo "0")
    log_warn "  Desired: $DESIRED, Ready: $READY"
    
    if [ "$DESIRED" == "$READY" ] && [ "$READY" -gt 0 ]; then
        log_success "✓ All validator pods are ready"
    else
        log_warn "⚠ Not all validator pods are ready"
    fi
else
    log_warn "⚠ Validator StatefulSet not found"
fi

# Check sentries
log_warn "Checking sentries..."
SENTRY_STS=$(kubectl get statefulset besu-sentry -n "$NAMESPACE" -o name 2>/dev/null || echo "")
if [ -n "$SENTRY_STS" ]; then
    log_success "✓ Sentry StatefulSet exists"
    
    DESIRED=$(kubectl get statefulset besu-sentry -n "$NAMESPACE" -o jsonpath='{.spec.replicas}' 2>/dev/null || echo "0")
    READY=$(kubectl get statefulset besu-sentry -n "$NAMESPACE" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || echo "0")
    log_warn "  Desired: $DESIRED, Ready: $READY"
    
    if [ "$DESIRED" == "$READY" ] && [ "$READY" -gt 0 ]; then
        log_success "✓ All sentry pods are ready"
    else
        log_warn "⚠ Not all sentry pods are ready"
    fi
else
    log_warn "⚠ Sentry StatefulSet not found"
fi

# Check RPC nodes
log_warn "Checking RPC nodes..."
RPC_STS=$(kubectl get statefulset besu-rpc -n "$NAMESPACE" -o name 2>/dev/null || echo "")
if [ -n "$RPC_STS" ]; then
    log_success "✓ RPC StatefulSet exists"
    
    DESIRED=$(kubectl get statefulset besu-rpc -n "$NAMESPACE" -o jsonpath='{.spec.replicas}' 2>/dev/null || echo "0")
    READY=$(kubectl get statefulset besu-rpc -n "$NAMESPACE" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || echo "0")
    log_warn "  Desired: $DESIRED, Ready: $READY"
    
    if [ "$DESIRED" == "$READY" ] && [ "$READY" -gt 0 ]; then
        log_success "✓ All RPC pods are ready"
    else
        log_warn "⚠ Not all RPC pods are ready"
    fi
else
    log_warn "⚠ RPC StatefulSet not found"
fi

# Check health checks
log_warn "Checking health checks..."
VALIDATOR_PODS=$(kubectl get pods -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || echo "")

if [ -n "$VALIDATOR_PODS" ]; then
    # Check if pod has health check probes
    LIVENESS=$(kubectl get pod "$VALIDATOR_PODS" -n "$NAMESPACE" -o jsonpath='{.spec.containers[0].livenessProbe.httpGet.path}' 2>/dev/null || echo "")
    READINESS=$(kubectl get pod "$VALIDATOR_PODS" -n "$NAMESPACE" -o jsonpath='{.spec.containers[0].readinessProbe.httpGet.path}' 2>/dev/null || echo "")
    
    if [ "$LIVENESS" == "/metrics" ]; then
        log_success "✓ Liveness probe is configured correctly"
    else
        log_warn "⚠ Liveness probe path: $LIVENESS"
    fi
    
    if [ "$READINESS" == "/metrics" ]; then
        log_success "✓ Readiness probe is configured correctly"
    else
        log_warn "⚠ Readiness probe path: $READINESS"
    fi
else
    log_warn "⚠ No validator pods found for health check validation"
fi

# Test pod restart
log_warn "Testing pod restart..."
if [ -n "$VALIDATOR_PODS" ]; then
    log_warn "  Restarting pod: $VALIDATOR_PODS"
    kubectl delete pod "$VALIDATOR_PODS" -n "$NAMESPACE" --wait=false
    
    # Wait for pod to be ready
    log_warn "  Waiting for pod to be ready..."
    if kubectl wait --for=condition=ready pod -l component=validator -n "$NAMESPACE" --timeout=300s 2>/dev/null; then
        log_success "✓ Pod restarted successfully"
    else
        log_warn "⚠ Pod restart test inconclusive"
    fi
else
    log_warn "⚠ No pods available for restart test"
fi

# Check services
log_warn "Checking services..."
SERVICES=("besu-validator" "besu-sentry" "besu-rpc")

for svc in "${SERVICES[@]}"; do
    if kubectl get service "$svc" -n "$NAMESPACE" &>/dev/null; then
        log_success "✓ Service $svc exists"
    else
        log_warn "⚠ Service $svc not found"
    fi
done

# Check ConfigMaps
log_warn "Checking ConfigMaps..."
CONFIGMAPS=("besu-validator-config" "besu-sentry-config" "besu-rpc-config")

for cm in "${CONFIGMAPS[@]}"; do
    if kubectl get configmap "$cm" -n "$NAMESPACE" &>/dev/null; then
        log_success "✓ ConfigMap $cm exists"
    else
        log_warn "⚠ ConfigMap $cm not found"
    fi
done

log_success "Deployment validation completed"

