#!/usr/bin/env bash

# Validate HPA Configuration
# This script validates that HPA is correctly configured and working

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 HPA Configuration..."

# Check if HPA exists
log_warn "Checking HPA..."
if kubectl get hpa besu-rpc-hpa -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ HPA besu-rpc-hpa exists"
    
    # Get HPA details
    log_warn "HPA Details:"
    kubectl get hpa besu-rpc-hpa -n "$NAMESPACE" -o yaml | grep -A 10 "spec:"
else
    log_warn "⚠ HPA not found, applying..."
    kubectl apply -f "$PROJECT_ROOT/k8s/base/rpc/hpa.yaml"
fi

# Validate HPA configuration
log_warn "Validating HPA configuration..."

# Check min replicas
MIN_REPLICAS=$(kubectl get hpa besu-rpc-hpa -n "$NAMESPACE" -o jsonpath='{.spec.minReplicas}' 2>/dev/null || echo "")
if [ "$MIN_REPLICAS" == "2" ]; then
    log_success "✓ Min replicas is set to 2"
else
    log_warn "⚠ Min replicas is $MIN_REPLICAS (expected 2)"
fi

# Check max replicas
MAX_REPLICAS=$(kubectl get hpa besu-rpc-hpa -n "$NAMESPACE" -o jsonpath='{.spec.maxReplicas}' 2>/dev/null || echo "")
if [ "$MAX_REPLICAS" == "10" ]; then
    log_success "✓ Max replicas is set to 10"
else
    log_warn "⚠ Max replicas is $MAX_REPLICAS (expected 10)"
fi

# Check metrics
METRICS=$(kubectl get hpa besu-rpc-hpa -n "$NAMESPACE" -o jsonpath='{.spec.metrics[*].type}' 2>/dev/null || echo "")
if echo "$METRICS" | grep -q "Resource"; then
    log_success "✓ Resource metrics configured"
else
    log_warn "⚠ Resource metrics not found"
fi

# Check if target StatefulSet exists
log_warn "Checking target StatefulSet..."
if kubectl get statefulset besu-rpc -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ Target StatefulSet besu-rpc exists"
    
    # Check current replicas
    CURRENT_REPLICAS=$(kubectl get statefulset besu-rpc -n "$NAMESPACE" -o jsonpath='{.spec.replicas}' 2>/dev/null || echo "")
    log_warn "Current replicas: $CURRENT_REPLICAS"
    
    # Check HPA status
    log_warn "HPA Status:"
    kubectl get hpa besu-rpc-hpa -n "$NAMESPACE" -o jsonpath='{.status}' | jq '.' 2>/dev/null || kubectl get hpa besu-rpc-hpa -n "$NAMESPACE"
else
    log_warn "⚠ Target StatefulSet besu-rpc not found"
fi

# Test autoscaling (if metrics server is available)
log_warn "Testing autoscaling..."
if kubectl top nodes &>/dev/null; then
    log_success "✓ Metrics server is available"
    log_warn "Note: HPA will scale based on CPU/memory usage"
    log_warn "To test autoscaling, generate load on RPC endpoints"
else
    log_warn "⚠ Metrics server not available (HPA requires metrics server)"
fi

log_success "HPA validation completed"

