#!/bin/bash
# Quick health check for a single translator service
# Usage: ./scripts/health-check.sh [IP]
# Example: ./scripts/health-check.sh 192.168.11.240

IP="${1:-192.168.11.240}"

echo "Health check for $IP..."

# Health endpoint
HEALTH=$(curl -s -m 3 http://$IP:9545/health 2>/dev/null)

if [ -z "$HEALTH" ]; then
    echo "❌ Service not responding"
    exit 1
fi

echo "$HEALTH" | jq '.' 2>/dev/null || echo "$HEALTH"

# Check upstream status
UPSTREAM_HEALTHY=$(echo "$HEALTH" | grep -o '"healthyCount":[0-9]*' | grep -o '[0-9]*')
UPSTREAM_TOTAL=$(echo "$HEALTH" | grep -o '"totalCount":[0-9]*' | grep -o '[0-9]*')

if [ "$UPSTREAM_HEALTHY" = "$UPSTREAM_TOTAL" ] && [ -n "$UPSTREAM_HEALTHY" ]; then
    echo ""
    echo "✅ All upstream nodes healthy ($UPSTREAM_HEALTHY/$UPSTREAM_TOTAL)"
    exit 0
else
    echo ""
    echo "⚠️  Upstream status: $UPSTREAM_HEALTHY/$UPSTREAM_TOTAL healthy"
    exit 1
fi
