#!/usr/bin/env bash
# NPS drift alert
# Compares this month’s survey ratings with last month and exits non-zero when the average drops, so cron can email you only when something is actually wrong.
#
# Category : Reporting
# Safety   : read only
# Uses     : reports run, surveys list
# Returns  : Month-over-month rating delta, with a non-zero exit on a decline.
#
# Requires the SendSquared CLI and jq:
#   curl -fsSL https://cli.sendsquared.com/install.sh | bash
#   sendsquared auth login
#
# Free to use and adapt. https://sendsquared.com/cli/scripts/#nps-drift

# Survey response pulse, month over month.
#
# survey_responses returns { data, cols } rather than a flat array: cols
# describes the columns the web app would render, data holds the rows. Read the
# shape before trusting any field name here, because the question set differs
# per survey.
set -euo pipefail
THIS_FROM=$(date -u +%Y-%m-01)
LAST_FROM=$(date -u -v-1m +%Y-%m-01 2>/dev/null || date -u -d "-1 month" +%Y-%m-01)
TODAY=$(date -u +%F)

count() {
  sendsquared reports run survey_responses --from "$1" --to "$2" 2>/dev/null \
    | jq '[.data.data[]?] | length'
}

NOW=$(count "$THIS_FROM" "$TODAY")
PREV=$(count "$LAST_FROM" "$THIS_FROM")

echo "survey responses"
printf "  last month : %s\n  this month : %s\n" "${PREV:-0}" "${NOW:-0}"

if [ "${PREV:-0}" -eq 0 ] && [ "${NOW:-0}" -eq 0 ]; then
  echo
  echo "No survey responses in either window. Check surveys are live:"
  echo "  sendsquared surveys list --stats"
  exit 0
fi

awk -v a="${PREV:-0}" -v b="${NOW:-0}" 'BEGIN {
  if (a == 0) { print "\n  first month with responses"; exit 0 }
  d = (b - a) * 100 / a
  printf "\n  change: %+.0f%%\n", d
  if (d < -20) { print "  DOWN sharply, worth a look"; exit 1 }
  print "  within normal range"
}'
