#!/usr/bin/env bash
# load-consumer-push.sh — Push-based consumer using `fafb-q bench sub`.
#
# Uses the built-in bench sub command for high-throughput consumption with
# native stats reporting. Logs throughput every LOG_INTERVAL seconds.
#
# Usage:
#   ./scripts/load-consumer-push.sh
#   GROUP=push-group-1 ./scripts/load-consumer-push.sh
#
# Requires: fafb-q CLI in PATH (or set FAFB_BIN).

set -euo pipefail

# ── Configurable variables ───────────────────────────────────────────────────
FAFB_BIN="${FAFB_BIN:-fafb-q}"                    # Path to fafb-q binary
SERVER="${SERVER:-localhost:9876}"                 # TCP server address
API_KEY="${API_KEY:-}"                             # API key (required)
NAMESPACE="${NAMESPACE:-default}"                  # Namespace
TOPIC="${TOPIC:-load-test}"                        # Topic name (supports wildcards)
GROUP="${GROUP:-push-consumer}"                    # Consumer group name
FROM_OFFSET="${FROM_OFFSET:-}"                    # Start offset (empty = head/latest)
COUNT="${COUNT:-}"                                 # Stop after N messages (empty = unlimited)
PROFILE="${PROFILE:-}"                            # Config profile (optional)
TLS="${TLS:-false}"                               # Enable TLS (true/false)
TLS_CA="${TLS_CA:-}"                              # CA cert path (optional)
# ─────────────────────────────────────────────────────────────────────────────

if [[ -z "$API_KEY" && -z "$PROFILE" ]]; then
    echo "ERROR: API_KEY or PROFILE must be set" >&2; exit 1
fi
command -v "$FAFB_BIN" &>/dev/null || { echo "ERROR: $FAFB_BIN not found" >&2; exit 1; }

FLAGS=()
if [[ -n "$PROFILE" ]]; then FLAGS+=(--profile "$PROFILE")
else FLAGS+=(--server "$SERVER" --api-key "$API_KEY"); fi
[[ "$TLS" == "true" ]] && FLAGS+=(--tls)
[[ -n "$TLS_CA" ]] && FLAGS+=(--tls-ca "$TLS_CA")

FULL_TOPIC="${NAMESPACE}/${TOPIC}"

echo "═══════════════════════════════════════════════════"
echo " fafb-q Push Consumer (bench sub)"
echo "═══════════════════════════════════════════════════"
echo " Server:   ${SERVER}"
echo " Topic:    ${FULL_TOPIC}"
echo " Group:    ${GROUP}"
echo " Offset:   ${FROM_OFFSET:-head (latest)}"
echo " Count:    ${COUNT:-unlimited}"
echo "═══════════════════════════════════════════════════"
echo ""

# Build bench sub command
SUB_FLAGS=("${FLAGS[@]}" --group "$GROUP")
[[ -n "$FROM_OFFSET" ]] && SUB_FLAGS+=(--from "$FROM_OFFSET")
[[ -n "$COUNT" ]] && SUB_FLAGS+=(--count "$COUNT")

# bench sub handles stats natively — just run it
exec "$FAFB_BIN" bench sub "$FULL_TOPIC" "${SUB_FLAGS[@]}"
