#!/usr/bin/env bash
# session-count-monitor.sh — Deterministic session count monitor.
#
# Runs every 4h via ai.openclaw.session-count-monitor LaunchAgent.
# Replaces c380a835 LLM-cron (Session Count Monitor) which burned
# ~120k tokens/day on gpt-5.4-mini for a task that is a one-liner.
#
# Thresholds are aligned to HEARTBEAT.md's session-count baseline:
#   ≤10  → SESSION_COUNT_OK (n sessions)   [log only, no Telegram]
#   >10  → WARNING (n sessions)            [send to Telegram]
#   >20  → CRITICAL (n sessions)           [send to Telegram]
#
# Rationale: normal operation is 5–7 sessions (5 agents plus occasional
# workers), so >10 indicates abnormal accumulation and >20 is a real incident.
# Every run logs a UTC timestamp to stdout; LaunchAgent captures stdout/stderr
# in /tmp/openclaw/session-count-monitor.log.
#
# Secrets: sourced from ~/.openclaw/.env (THR-49 single source of truth).
# Delivery: only WARNING, CRITICAL, and ERROR states send Telegram.

set -u -o pipefail

ENV_FILE="/Users/openclaw/.openclaw/.env"
if [ -r "$ENV_FILE" ]; then
  # shellcheck disable=SC1090
  set -a; . "$ENV_FILE"; set +a
else
  echo "FATAL env file unreadable: $ENV_FILE"; exit 2
fi

N=$(/opt/homebrew/bin/openclaw sessions --json 2>/dev/null \
    | python3 -c "import json,sys; print(json.load(sys.stdin)['totalCount'])" 2>/dev/null) || N=""

if [ -z "$N" ]; then
  MSG="SESSION_COUNT_ERROR: openclaw sessions failed or returned non-JSON"
elif [ "$N" -gt 20 ]; then
  MSG="CRITICAL ($N sessions)"
elif [ "$N" -gt 10 ]; then
  MSG="WARNING ($N sessions)"
else
  MSG="SESSION_COUNT_OK ($N sessions)"
fi

TS=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "$TS $MSG"

case "$MSG" in
SESSION_COUNT_OK*) ;;
*) /opt/homebrew/bin/openclaw message send --channel telegram --target 8032472383 -m "$MSG" ;;
esac
