#!/usr/bin/env bash
# Why didn’t my automation fire?
# The question the dashboard cannot answer. Replays every trigger evaluation for a workflow and groups the rejections by reason, so you see exactly which condition is eliminating contacts.
#
# Category : Diagnostics
# Safety   : read only
# Uses     : events triggers, workflows list
# Returns  : Fired vs rejected counts, then rejection reasons ranked by frequency.
#
# 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/#why-didnt-it-fire

# Usage: ./why-didnt-it-fire.sh [workflowId] [sinceYYYY-MM-DD]
# With no workflow id it reports across every automation.
set -euo pipefail
WORKFLOW=${1:-}
SINCE=${2:-$(date -u -v-7d +%F 2>/dev/null || date -u -d "-7 days" +%F)}

EV=$(sendsquared events triggers --limit 1000 --from "$SINCE" ${WORKFLOW:+--workflow "$WORKFLOW"})
N=$(jq '.data | length' <<<"$EV")
echo "--- $N trigger evaluations since $SINCE"

echo
echo "outcome"
jq -r '.data[].outcome // "unknown"' <<<"$EV" | sort | uniq -c | sort -rn

echo
echo "why contacts were rejected (the message the engine recorded)"
jq -r '.data[] | select(.outcome != "fired") | .message // "no message recorded"' <<<"$EV" \
  | sed 's/[0-9]\{4,\}/<id>/g' | sort | uniq -c | sort -rn | head -15

echo
echo "by automation"
jq -r '.data[] | "\(.outcome)\t\(.workflow_name // ("workflow " + (.workflow_id|tostring)))"' <<<"$EV" \
  | sort | uniq -c | sort -rn | head -15
