#!/bin/bash
# Runs one weekly fetch script and texts Jason if it fails.
# Called by the launchd jobs:  run_with_alert.sh <label> <script.py> <data json>
#
# "Failed" means any of:
#   - the script exits with an error (e.g. an API renamed a field)
#   - the data JSON was not rewritten by this run
#   - podcast: the run finished without Podbean numbers
#   - video:   YouTube watch-time (Analytics OAuth) failed and was left blank
#   - email:   link-click details were skipped for more than 5 campaigns
# A failure is retried once after 10 minutes before alerting, to ride out short network blips.
#
# Set DRY_RUN=1 to print the alert instead of sending it.

LABEL="$1"
SCRIPT="$2"
JSON="$3"
DIR="/Users/jwdavis/swapa_analytics"
PHONE="+18178001061"
RETRY_WAIT="${RETRY_WAIT:-600}"

cd "$DIR" || exit 1

run_once() {
  local start out err
  start=$(date +%s)
  out=$(mktemp); err=$(mktemp)
  /usr/bin/python3 "$SCRIPT" >"$out" 2>"$err"
  local code=$?
  cat "$out"; cat "$err" >&2          # keep the normal log files complete
  REASON=""
  if [ $code -ne 0 ]; then
    REASON="crashed: $(grep -v '^\s*$' "$err" | tail -1 | cut -c1-140)"
  elif [ ! -f "$JSON" ] || [ "$(stat -f %m "$JSON")" -lt "$start" ]; then
    REASON="ran but did not update $(basename "$JSON")"
  elif [ "$LABEL" = "Podcast" ] && grep -q "Podbean data present: *no" "$out"; then
    REASON="Podbean numbers missing (external downloads will be blank)"
  elif [ "$LABEL" = "Podcast" ] && [ "$(grep -c 'Stats fetch failed' "$out")" -gt 5 ]; then
    REASON="Podbean stats failed for $(grep -c 'Stats fetch failed' "$out") episodes (monthly public listens will be low)"
  elif [ "$LABEL" = "Video" ] && grep -q "YouTube Analytics error" "$out"; then
    REASON="YouTube watch-time data missing ($(grep -m1 'YouTube Analytics error' "$out" | sed 's/.*error: //' | cut -c1-100))"
  elif [ "$LABEL" = "Email" ] && [ "$(grep -c 'skipping campaign' "$out")" -gt 5 ]; then
    REASON="link-click details skipped for $(grep -c 'skipping campaign' "$out") campaigns (top links will be incomplete)"
  fi
  rm -f "$out" "$err"
  [ -z "$REASON" ]
}

if run_once; then exit 0; fi
echo "[$(date)] $LABEL failed ($REASON) — retrying in ${RETRY_WAIT}s" >&2
sleep "$RETRY_WAIT"
if run_once; then exit 0; fi

MSG="⚠️ SWAPA $LABEL stats fetch failed — $REASON. Dashboard may be out of date or missing numbers. Check ~/swapa_analytics/logs."
echo "[$(date)] ALERT: $MSG" >&2
if [ "${DRY_RUN:-0}" = "1" ]; then
  echo "DRY_RUN — would text $PHONE: $MSG"
else
  /usr/bin/osascript - "$MSG" "$PHONE" <<'APPLESCRIPT'
on run argv
  tell application "Messages" to send (item 1 of argv) to participant (item 2 of argv) of (1st service whose service type = iMessage)
end run
APPLESCRIPT
fi
exit 1
