#!/bin/bash
# x_feed 정기수집 (하루 2회) + 실패 알림 + 성공 타임스탬프
BASE="$HOME/Claude/Projects/에이전트구축"
cd "$BASE" || exit 1
PY=/opt/homebrew/bin/python3
STAMP="$BASE/.xfeed_last_ok"

before=$(wc -l < x_feed.jsonl 2>/dev/null || echo 0)
bash "$BASE/run_xfeed.sh" >> "$BASE/xfeed_2x.log" 2>&1
after=$(wc -l < x_feed.jsonl 2>/dev/null || echo 0)
added=$((after - before))

if [ "$added" -gt 0 ]; then
  date -u +%s > "$STAMP"
  echo "$(date '+%F %T') OK +${added}" >> "$BASE/xfeed_2x.log"
else
  "$PY" - << PYEOF
import re, urllib.request, urllib.parse, json
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] 수집 실패 — 신규 0건. 크롬/CDP 확인 필요"
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') FAIL 0건" >> "$BASE/xfeed_2x.log"
fi
