#!/bin/bash
# x_feed 정체 감시 — 수집 잡과 별개 경로. 마지막 성공이 16시간 넘으면 알림
BASE="$HOME/Claude/Projects/에이전트구축"
cd "$BASE" || exit 1
PY=/opt/homebrew/bin/python3
STAMP="$BASE/.xfeed_last_ok"
LIMIT=57600   # 16시간

now=$(date -u +%s)
if [ -f "$STAMP" ]; then last=$(cat "$STAMP"); else last=0; fi
gap=$(( (now - last) / 3600 ))

if [ $((now - last)) -gt $LIMIT ]; then
  GAP="$gap" "$PY" - << 'PYEOF'
import re, os, urllib.request, urllib.parse
s = open("nq_levels.py", encoding="utf-8").read()
tok = re.search(r'BOT_TOKEN\s*=\s*["\']([^"\']+)', s).group(1)
cid = re.search(r'CHAT_ID\s*=\s*["\']?([^"\'\s]+)', s).group(1)
msg = "[x_feed] 정체 경보 — 마지막 성공 %s시간 전. launchd 잡 확인 필요" % os.environ.get("GAP","?")
d = urllib.parse.urlencode({"chat_id": cid, "text": msg}).encode()
urllib.request.urlopen(f"https://api.telegram.org/bot{tok}/sendMessage", d, timeout=15)
PYEOF
  echo "$(date '+%F %T') WATCHDOG 경보 ${gap}h" >> "$BASE/xfeed_2x.log"
fi
