#!/usr/bin/env bash
# Validate Besu containers in temporary VM
# Checks health, connectivity, and configuration

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

TEMP_VM_IP="${BESU_TEMP_IP:-192.168.11.90}"
BESU_DATA="/opt/besu"

log_info() { echo "[INFO] $1"; }
log_success() { echo "[✓] $1"; }
log_warn() { echo "[WARNING] $1"; }
log_error() { echo "[ERROR] $1"; }

log_info "Validating Besu containers in temporary VM ($TEMP_VM_IP)..."

# Check VM accessibility
if ! ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 "root@$TEMP_VM_IP" "echo 'VM accessible'" 2>/dev/null; then
    log_error "Cannot access temporary VM at $TEMP_VM_IP"
    exit 1
fi

log_success "VM is accessible"

# Check Docker
log_info "Checking Docker..."
if ! ssh "root@$TEMP_VM_IP" "docker --version" >/dev/null 2>&1; then
    log_error "Docker is not installed or not accessible"
    exit 1
fi

log_success "Docker is running"

# Check containers
log_info "Checking container status..."
CONTAINERS=$(ssh "root@$TEMP_VM_IP" "docker ps --format '{{.Names}}' | grep '^besu-'")

if [[ -z "$CONTAINERS" ]]; then
    log_error "No Besu containers found"
    exit 1
fi

CONTAINER_COUNT=$(echo "$CONTAINERS" | wc -l)
log_success "Found $CONTAINER_COUNT Besu containers"

# Check each container
FAILED=0
for container in $CONTAINERS; do
    log_info "Checking $container..."
    
    # Check if container is running
    if ! ssh "root@$TEMP_VM_IP" "docker ps --format '{{.Names}}' | grep -q '^$container$'" 2>/dev/null; then
        log_error "$container is not running"
        FAILED=$((FAILED + 1))
        continue
    fi
    
    # Check health
    HEALTH=$(ssh "root@$TEMP_VM_IP" "docker inspect --format='{{.State.Health.Status}}' $container" 2>/dev/null || echo "no-healthcheck")
    if [[ "$HEALTH" == "healthy" ]]; then
        log_success "$container is healthy"
    elif [[ "$HEALTH" == "no-healthcheck" ]]; then
        log_warn "$container has no healthcheck configured"
    else
        log_warn "$container health status: $HEALTH"
    fi
    
    # Check logs for errors
    ERROR_COUNT=$(ssh "root@$TEMP_VM_IP" "docker logs $container 2>&1 | grep -i 'error\|exception\|fatal' | wc -l" 2>/dev/null || echo "0")
    if [[ "$ERROR_COUNT" -gt 0 ]]; then
        log_warn "$container has $ERROR_COUNT error messages in logs"
    fi
done

# Check RPC endpoints
log_info "Checking RPC endpoints..."
RPC_CONTAINERS=$(echo "$CONTAINERS" | grep "rpc")

for container in $RPC_CONTAINERS; do
    # Extract port from container name (rpc-1 -> 8545, rpc-2 -> 8547, etc.)
    RPC_NUM=$(echo "$container" | sed 's/besu-rpc-//')
    if [[ "$RPC_NUM" == "1" ]]; then
        RPC_PORT=8545
    elif [[ "$RPC_NUM" == "2" ]]; then
        RPC_PORT=8547
    elif [[ "$RPC_NUM" == "3" ]]; then
        RPC_PORT=8549
    else
        continue
    fi
    
    log_info "Testing RPC endpoint for $container on port $RPC_PORT..."
    RESPONSE=$(ssh "root@$TEMP_VM_IP" "curl -s -X POST -H 'Content-Type: application/json' --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' http://localhost:$RPC_PORT" 2>/dev/null || echo "")
    
    if echo "$RESPONSE" | grep -q "result"; then
        BLOCK_NUM=$(echo "$RESPONSE" | grep -o '"result":"[^"]*"' | cut -d'"' -f4)
        log_success "$container RPC is responding (block: $BLOCK_NUM)"
    else
        log_warn "$container RPC is not responding correctly"
        FAILED=$((FAILED + 1))
    fi
done

# Check metrics endpoints
log_info "Checking metrics endpoints..."
for container in $CONTAINERS; do
    # Extract metrics port
    if echo "$container" | grep -q "validator-1"; then
        METRICS_PORT=9545
    elif echo "$container" | grep -q "validator-2"; then
        METRICS_PORT=9546
    elif echo "$container" | grep -q "validator-3"; then
        METRICS_PORT=9547
    elif echo "$container" | grep -q "validator-4"; then
        METRICS_PORT=9548
    elif echo "$container" | grep -q "validator-5"; then
        METRICS_PORT=9549
    elif echo "$container" | grep -q "sentry-1"; then
        METRICS_PORT=9550
    elif echo "$container" | grep -q "sentry-2"; then
        METRICS_PORT=9551
    elif echo "$container" | grep -q "sentry-3"; then
        METRICS_PORT=9552
    elif echo "$container" | grep -q "sentry-4"; then
        METRICS_PORT=9553
    elif echo "$container" | grep -q "rpc-1"; then
        METRICS_PORT=9554
    elif echo "$container" | grep -q "rpc-2"; then
        METRICS_PORT=9555
    elif echo "$container" | grep -q "rpc-3"; then
        METRICS_PORT=9556
    else
        continue
    fi
    
    METRICS_RESPONSE=$(ssh "root@$TEMP_VM_IP" "curl -s http://localhost:$METRICS_PORT/metrics" 2>/dev/null || echo "")
    if echo "$METRICS_RESPONSE" | grep -q "besu"; then
        log_success "$container metrics endpoint is responding"
    else
        log_warn "$container metrics endpoint is not responding"
    fi
done

# Check data directories
log_info "Checking data directories..."
for container in $CONTAINERS; do
    DATA_SIZE=$(ssh "root@$TEMP_VM_IP" "docker exec $container du -sh /data/besu 2>/dev/null | cut -f1" || echo "unknown")
    log_info "$container data size: $DATA_SIZE"
done

# Summary
log_info ""
log_info "Validation Summary:"
log_info "  Containers found: $CONTAINER_COUNT"
log_info "  Failed checks: $FAILED"

if [[ $FAILED -eq 0 ]]; then
    log_success "All checks passed!"
    exit 0
else
    log_warn "Some checks failed. Please review the output above."
    exit 1
fi

