#!/bin/bash
set -euo pipefail

HOST="${HEALTH_CHECK_HOST:-localhost}"
PORT="${HEALTH_CHECK_PORT:-8080}"
MAX_RETRIES=10
RETRY_INTERVAL=3

usage() {
    echo "Usage: $0 [--help]"
    echo "Check health of Azaion.Detections service."
    echo ""
    echo "Environment variables:"
    echo "  HEALTH_CHECK_HOST  Target host (default: localhost)"
    echo "  HEALTH_CHECK_PORT  Target port (default: 8080)"
    exit 0
}

for arg in "$@"; do
    case "$arg" in
        --help) usage ;;
    esac
done

URL="http://${HOST}:${PORT}/health"
echo "Checking health at $URL ..."

for i in $(seq 1 "$MAX_RETRIES"); do
    if curl -sf "$URL" > /dev/null 2>&1; then
        RESPONSE="$(curl -sf "$URL")"
        echo "Health check passed (attempt $i/$MAX_RETRIES): $RESPONSE"
        exit 0
    fi
    echo "Attempt $i/$MAX_RETRIES failed, retrying in ${RETRY_INTERVAL}s..."
    sleep "$RETRY_INTERVAL"
done

echo "ERROR: Health check failed after $MAX_RETRIES attempts."
exit 1
