#!/usr/bin/env bash
set -u

LEVEL=health
SCENARIO="${SDKHARNESS_SCENARIO:-}"
HERE="$(cd "$(dirname "$0")" && pwd -P)"
. "$HERE/lib/contract.sh"
result() { printf 'SDKHARNESS_RESULT\t%s\t%s\t%s\t%s\n' "$LEVEL" "$SCENARIO" "$1" "$2"; }

[ "${SDKHARNESS_TEST_LEVEL:-}" = "$LEVEL" ] && [ "$SCENARIO" = golden-path ] \
  || { result FAIL 'configuration: unexpected contract identity'; exit 1; }
[ -n "${SDKHARNESS_SIMULATOR_URL:-}" ] && sdkharness_valid_loopback_origin "$SDKHARNESS_SIMULATOR_URL" \
  || { result FAIL 'configuration: simulator URL must be an IPv4 loopback HTTP origin'; exit 1; }
log="$(mktemp "${TMPDIR:-/tmp}/sdkharness-blazer-health.XXXXXX")" \
  || { result FAIL 'setup: could not create child log'; exit 1; }
trap 'rm -f "$log"' EXIT
# Only the simulator's fixed credential may reach the check; every ambient B2_* is dropped
# (the bucket name is kept: it is a name, not a secret, and the simulator creates it).
bucket="${B2_BUCKET_NAME:-}"
for name in $(compgen -e); do case "$name" in B2_*) unset "$name" ;; esac; done
export B2_APPLICATION_KEY_ID=test-key-id B2_APPLICATION_KEY=test-key \
  B2_TEST_APPLICATION_KEY_ID=test-key-id B2_TEST_APPLICATION_KEY=test-key
[ -z "$bucket" ] || export B2_BUCKET_NAME="$bucket"
if HEALTHCHECK_REALM_URL="$SDKHARNESS_SIMULATOR_URL" "$HERE/health/golden-path" >"$log" 2>&1; then
  child_rc=0
else
  child_rc=$?
fi
prefix='HEALTHCHECK blazer: '
grep -Fv "$prefix" "$log" || true
count="$(grep -Fc "$prefix" "$log" 2>/dev/null || true)"
[ "$count" = 1 ] || { result FAIL "contract: expected one health result, got $count"; exit 1; }
verdict="$(grep -F "$prefix" "$log")"; verdict="${verdict#*: }"
case "$verdict" in
  PASS) [ "$child_rc" = 0 ] || { result FAIL "contract: PASS exited $child_rc"; exit 1; }; result PASS - ;;
  'FAIL ('*')') reason="${verdict#FAIL (}"; result FAIL "${reason%)}"; exit 1 ;;
  'SKIP ('*')')
    # A check that reports SKIP and then fails is broken, not amber.
    [ "$child_rc" = 0 ] || { result FAIL "contract: SKIP exited $child_rc"; exit 1; }
    reason="${verdict#SKIP (}"; result SKIP "${reason%)} -- health executable could not run" ;;
  *) result FAIL 'contract: malformed health verdict'; exit 1 ;;
esac
