#!/bin/bash
# Fires a desktop notification when a live session has been idle/waiting past
# a threshold. Deduped per idle period (sessionId + statusUpdatedAt), so each
# idle stretch pings once. Run periodically by a launchd agent.

reg="$HOME/.claude/sessions"
statefile="$HOME/.claude/hooks/.idle_notified"
now="$(date +%s)"

THRESHOLD=60    # seconds idle before the ping
CEILING=900     # older-than-this idle sessions are "moved on"; don't ping

find_notifier() {
  if command -v terminal-notifier >/dev/null 2>&1; then command -v terminal-notifier; return; fi
  for p in /opt/homebrew/bin/terminal-notifier /usr/local/bin/terminal-notifier; do
    [ -x "$p" ] && { echo "$p"; return; }
  done
}
notifier="$(find_notifier)"
[ -z "$notifier" ] && exit 0

touch "$statefile"

shopt -s nullglob
for f in "$reg"/*.json; do
  pid="$(jq -r '.pid // empty' "$f" 2>/dev/null)"
  [ -z "$pid" ] && continue
  kill -0 "$pid" 2>/dev/null || continue

  st="$(jq -r '.status // empty' "$f" 2>/dev/null)"
  case "$st" in
    idle|waiting) ;;
    *) continue ;;
  esac

  sua="$(jq -r '.statusUpdatedAt // .updatedAt // 0' "$f" 2>/dev/null)"
  sua_s=$(( sua / 1000 ))
  idle_age=$(( now - sua_s ))

  if [ "$idle_age" -ge "$THRESHOLD" ] && [ "$idle_age" -lt "$CEILING" ]; then
    sid="$(jq -r '.sessionId // empty' "$f" 2>/dev/null)"
    key="$sid:$sua"
    if ! grep -qF "$key" "$statefile" 2>/dev/null; then
      name="$(jq -r '.name // "session"' "$f" 2>/dev/null)"
      "$notifier" -title "Claude Code · idle ${idle_age}s" -subtitle "$name" \
        -message "Idle for ${idle_age}s - waiting for you" -sound default 2>/dev/null
      echo "$key" >> "$statefile"
    fi
  fi
done

tail -n 300 "$statefile" > "$statefile.tmp" 2>/dev/null && mv -f "$statefile.tmp" "$statefile"
