#!/usr/bin/env bash
# wa_watch.sh — WhatsApp reader dead-man's switch (launchd, every 15 min).
#
# Reads heartbeat.json the daemon refreshes every 60s. Alerts Ahmed on
# Telegram (via the Ultron VPS notify bot) when:
#   - the heartbeat is STALE (>5 min)  -> the daemon process itself is dead
#   - open=false for two checks in a row -> daemon alive but WhatsApp
#     disconnected (logged out on phone / ban / long offline)
# 2h cooldown per alert kind so a bad night doesn't spam him.
set -uo pipefail
cd "$(dirname "$0")"
HB=heartbeat.json
STATE=.wa_watch_state
NOW=$(date +%s)

state_get() { grep "^$1=" "$STATE" 2>/dev/null | cut -d= -f2; }
state_set() {
  grep -v "^$1=" "$STATE" 2>/dev/null > "$STATE.tmp" || true
  echo "$1=$2" >> "$STATE.tmp"; mv "$STATE.tmp" "$STATE"
}
alert() { # $1=kind $2=message
  local last; last=$(state_get "cool_$1"); last=${last:-0}
  if (( NOW - last < 7200 )); then return; fi
  if ssh -o ConnectTimeout=10 ultron "cd /root/ultron && node scripts/notify.js \"$2\"" >/dev/null 2>&1; then
    state_set "cool_$1" "$NOW"
  fi
}

if [[ ! -f $HB ]]; then
  alert dead "WhatsApp reader: no heartbeat file — daemon has never started or was wiped. Check launchctl list | grep whatsapp-reader on the Mac."
  exit 0
fi

TS=$(python3 -c "import json;print(json.load(open('$HB')).get('ts',0)//1000)" 2>/dev/null || echo 0)
OPEN=$(python3 -c "import json;print(1 if json.load(open('$HB')).get('open') else 0)" 2>/dev/null || echo 0)

if (( NOW - TS > 300 )); then
  alert dead "WhatsApp reader DAEMON IS DEAD (heartbeat stale $(( (NOW-TS)/60 )) min). launchd should restart it; if this repeats, check daemon.log on the Mac."
  exit 0
fi

if [[ $OPEN == 0 ]]; then
  if [[ $(state_get lastopen) == 0 ]]; then
    alert disc "WhatsApp reader is DISCONNECTED from WhatsApp (daemon alive, socket down for 15+ min). If it doesn't self-heal: check phone > Linked Devices — the session may be logged out and need a new QR."
  fi
  state_set lastopen 0
else
  state_set lastopen 1
fi
