#!/bin/bash
# mahally-intel watchdog — keeps the product-intel scraper alive unattended (cron */10min).
# Self-heals both failure modes: a CRASH (process gone) and a STALL (alive but details.jsonl frozen).
# Stops relaunching once done (details rows >= product rows) or when legitimately PAUSED (proxy dry).
cd /root/ultron || exit 0
D=data/mahally
[ -f "$D/PAUSED" ] && exit 0                                   # proxy exhausted → its own auto-resume owns it
PROD=$(wc -l < "$D/products.jsonl" 2>/dev/null || echo 0)
DET=$(wc -l < "$D/details.jsonl" 2>/dev/null || echo 0)
[ "$PROD" -gt 0 ] && [ "$DET" -ge "$PROD" ] && exit 0          # finished — nothing to do

RUNNING=$(pgrep -f "[s]crape-mahally-intel.js" | head -1)
STATE="down"
if [ -n "$RUNNING" ]; then
  AGE=$(( $(date +%s) - $(stat -c %Y "$D/details.jsonl" 2>/dev/null || echo 0) ))
  [ "$AGE" -le 1200 ] && exit 0                                # alive and writing within 20min → fine
  STATE="stalled_${AGE}s"
  pkill -9 -f "[s]crape-mahally-intel.js"; sleep 3
fi

# crashed/killed/stalled → relaunch (resumes from the details cursor; nothing re-fetched)
setsid bash -c "exec env CONC=24 node src/scrape-mahally-intel.js enum details >> $D/intel.log 2>&1" </dev/null >/dev/null 2>&1 &
{ node scripts/notify.js "🔧 Mahally-intel watchdog restarted it (was $STATE) — ${DET}/${PROD} products done"; } 2>/dev/null || true
