#!/usr/bin/env bash

# Validate VM deployment
# This script validates that all VMs are properly deployed and configured

set -e

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

# Configuration
RESOURCE_GROUP="${RESOURCE_GROUP:-defi-oracle-mainnet-rg}"
VALIDATOR_COUNT="${VALIDATOR_COUNT:-2}"
SENTRY_COUNT="${SENTRY_COUNT:-2}"
RPC_COUNT="${RPC_COUNT:-2}"


log_success "Validating VM deployment..."

# Check prerequisites
if ! command -v az &> /dev/null; then
    log_error "Error: Azure CLI not found"
    exit 1
fi

if ! az account show &> /dev/null; then
    log_error "Error: Not logged in to Azure"
    exit 1
fi

# Get VM list
log_warn "Getting VM list..."
VMS=$(az vm list --resource-group "$RESOURCE_GROUP" --query "[].{Name:name, PowerState:powerState, IP:publicIps}" -o json 2>/dev/null || echo "[]")

if [ "$VMS" == "[]" ]; then
    log_error "Error: No VMs found in resource group"
    exit 1
fi

VALIDATOR_VMS=$(echo "$VMS" | jq -r '.[] | select(.Name | contains("validator")) | .Name')
SENTRY_VMS=$(echo "$VMS" | jq -r '.[] | select(.Name | contains("sentry")) | .Name')
RPC_VMS=$(echo "$VMS" | jq -r '.[] | select(.Name | contains("rpc")) | .Name')

# Validate validator VMs
log_warn "Validating validator VMs..."
VALIDATOR_COUNT_FOUND=$(echo "$VALIDATOR_VMS" | grep -c . || echo "0")
if [ "$VALIDATOR_COUNT_FOUND" -lt "$VALIDATOR_COUNT" ]; then
    log_error "✗ Expected $VALIDATOR_COUNT validators, found $VALIDATOR_COUNT_FOUND"
else
    log_success "✓ Found $VALIDATOR_COUNT_FOUND validator VMs"
fi

# Validate sentry VMs
log_warn "Validating sentry VMs..."
SENTRY_COUNT_FOUND=$(echo "$SENTRY_VMS" | grep -c . || echo "0")
if [ "$SENTRY_COUNT_FOUND" -lt "$SENTRY_COUNT" ]; then
    log_error "✗ Expected $SENTRY_COUNT sentries, found $SENTRY_COUNT_FOUND"
else
    log_success "✓ Found $SENTRY_COUNT_FOUND sentry VMs"
fi

# Validate RPC VMs
log_warn "Validating RPC VMs..."
RPC_COUNT_FOUND=$(echo "$RPC_VMS" | grep -c . || echo "0")
if [ "$RPC_COUNT_FOUND" -lt "$RPC_COUNT" ]; then
    log_error "✗ Expected $RPC_COUNT RPC nodes, found $RPC_COUNT_FOUND"
else
    log_success "✓ Found $RPC_COUNT_FOUND RPC VMs"
fi

# Check VM status
log_warn "Checking VM status..."
for VM in $VALIDATOR_VMS $SENTRY_VMS $RPC_VMS; do
    STATUS=$(az vm show --resource-group "$RESOURCE_GROUP" --name "$VM" --show-details --query "powerState" -o tsv 2>/dev/null || echo "unknown")
    if [ "$STATUS" == "VM running" ]; then
        log_success "✓ $VM is running"
    else
        log_error "✗ $VM status: $STATUS"
    fi
done

# Check Besu containers
log_warn "Checking Besu containers..."
for VM in $SENTRY_VMS $RPC_VMS; do
    IP=$(az vm show --resource-group "$RESOURCE_GROUP" --name "$VM" --show-details --query "publicIps" -o tsv 2>/dev/null || echo "")
    if [ -n "$IP" ] && [ "$IP" != "None" ]; then
        if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$IP "docker ps | grep -q besu" 2>/dev/null; then
            log_success "✓ $VM: Besu container is running"
        else
            log_error "✗ $VM: Besu container is not running"
        fi
    fi
done

# Check RPC endpoints
log_warn "Checking RPC endpoints..."
for VM in $RPC_VMS; do
    IP=$(az vm show --resource-group "$RESOURCE_GROUP" --name "$VM" --show-details --query "publicIps" -o tsv 2>/dev/null || echo "")
    if [ -n "$IP" ] && [ "$IP" != "None" ]; then
        RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" \
            --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
            http://$IP:8545 2>/dev/null || echo "")
        if echo "$RESPONSE" | jq -e '.result' > /dev/null 2>&1; then
            BLOCK_NUMBER=$(echo "$RESPONSE" | jq -r '.result')
            log_success "✓ $VM: RPC endpoint responding (block: $BLOCK_NUMBER)"
        else
            log_error "✗ $VM: RPC endpoint not responding"
        fi
    fi
done

log_success "Validation complete!"

