#!/usr/bin/env bash
# Release verification health check — called by deploy.sh step 14.
#
# Env vars (set by deploy.sh):
#   HEALTH_URL    Full URL to /health endpoint
#   HEALTH_TOKEN  Bearer token (from HEALTH_CHECK_TOKEN in .env)
#
# Exit codes:
#   0  healthy
#   1  degraded (operational but investigation recommended)
#   2  unhealthy or unreachable (triggers rollback in deploy.sh)

set -euo pipefail

: "${HEALTH_URL:?HEALTH_URL must be set}"
: "${HEALTH_TOKEN:?HEALTH_TOKEN must be set}"

MAX_ATTEMPTS=3
SLEEP_BETWEEN=5

attempt=0
while [[ $attempt -lt $MAX_ATTEMPTS ]]; do
    attempt=$((attempt + 1))

    HTTP_BODY=$(curl -s --max-time 20 \
        -H "Authorization: Bearer ${HEALTH_TOKEN}" \
        -w '\n__HTTP_CODE__%{http_code}' \
        "${HEALTH_URL}" 2>/dev/null) || true

    HTTP_CODE=$(echo "$HTTP_BODY" | grep '__HTTP_CODE__' | sed 's/__HTTP_CODE__//')
    BODY=$(echo "$HTTP_BODY" | grep -v '__HTTP_CODE__')

    if [[ -z "$HTTP_CODE" || "$HTTP_CODE" == "000" ]]; then
        echo "  attempt $attempt/$MAX_ATTEMPTS: connection failed (curl error)" >&2
        [[ $attempt -lt $MAX_ATTEMPTS ]] && sleep $SLEEP_BETWEEN
        continue
    fi

    if [[ "$HTTP_CODE" == "403" ]]; then
        echo "  /health returned 403 — HEALTH_CHECK_TOKEN mismatch" >&2
        exit 2
    fi

    if command -v jq &>/dev/null; then
        STATUS=$(echo "$BODY" | jq -r '.status // "unknown"' 2>/dev/null || echo "unknown")
    else
        STATUS=$(echo "$BODY" | grep -o '"status":"[^"]*"' | head -1 | sed 's/"status":"//;s/"//')
    fi

    case "$STATUS" in
        healthy)
            echo "  /health → healthy (HTTP $HTTP_CODE)"
            exit 0
            ;;
        degraded)
            echo "  /health → degraded (HTTP $HTTP_CODE) — operational but investigation recommended"
            exit 1
            ;;
        unhealthy)
            echo "  /health → unhealthy (HTTP $HTTP_CODE)"
            exit 2
            ;;
        *)
            echo "  /health → unexpected status '$STATUS' (HTTP $HTTP_CODE)" >&2
            [[ $attempt -lt $MAX_ATTEMPTS ]] && sleep $SLEEP_BETWEEN
            ;;
    esac
done

echo "  /health did not return a valid status after $MAX_ATTEMPTS attempts" >&2
exit 2
