#!/usr/bin/env bash
# One-shot morning verdict for the halacha night drain (scheduled 2026-06-15 04:30 UTC
# via chaim's crontab; throwaway — lives under data/, not tracked in scripts/).
# Captures whether last night's run (with the PR #251 fix: durable rate-limit
# detection + 05:00–07:00 catch-up window) actually drained the backlog.
# Baseline at install time (2026-06-14 13:xx IDT): pending=96 done=248 halachot=4099.
set -u
export HOME=/home/chaim
REPO=/home/chaim/legal-ai
PY="$REPO/mcp-server/.venv/bin/python"
OUT="$REPO/data/logs/halacha_night_report_$(TZ=Asia/Jerusalem date +%Y%m%d).md"
SUP_LOG=/home/chaim/.pm2/logs/legal-halacha-supervisor-out.log
DRAIN_ERR=/home/chaim/.pm2/logs/legal-halacha-drain-error.log
mkdir -p "$REPO/data/logs"

{
  echo "# דוח-בוקר: ריצת-הלכות הלילה — $(TZ=Asia/Jerusalem date '+%Y-%m-%d %H:%M %Z')"
  echo
  echo "בסיס-השוואה (אתמול 13:xx IDT): pending=96 · done=248 · halachot=4099"
  echo
  echo '## מצב נוכחי (supervisor status)'
  echo '```'
  cd "$REPO" && "$PY" scripts/halacha_drain_supervisor.py status 2>&1
  echo '```'
  echo
  echo '## פעולות המתזמר ב-12 השעות האחרונות (modes/actions)'
  echo '```'
  grep -E 'מצב:|פעולה:|catch-up|rate-limit|נעצר' "$SUP_LOG" 2>/dev/null | tail -40
  echo '```'
  echo
  echo '## אותות rate-limit בלוג-הדריינר (24ש אחרונות בלוג)'
  echo '```'
  echo "429 hits (tail 4000):  $(tail -4000 "$DRAIN_ERR" 2>/dev/null | grep -c '429')"
  echo "session-limit msgs:    $(tail -4000 "$DRAIN_ERR" 2>/dev/null | grep -c 'hit your session limit')"
  echo "extraction_failed:     $(tail -4000 "$DRAIN_ERR" 2>/dev/null | grep -c 'extraction_failed')"
  echo "hold-stopped (fix A):  $(grep -c 'hold-stopped' "$SUP_LOG" 2>/dev/null)"
  echo "catch-up opened (B):   $(grep -c 'catch-up בוקר' "$SUP_LOG" 2>/dev/null)"
  echo '```'
  echo
  echo "_(נוצר ע\"י data/halacha_night_check.sh; ניתן למחוק את שורת ה-crontab של 15.6.)_"
} > "$OUT" 2>&1

echo "report written: $OUT"
