#!/bin/bash
# Morning check: did the 02:00 parked-ingest resume drain the private realm
# queue, and is the pool healthy for daytime chat? Read-only except its own
# status file; notifies only when something needs attention.
set -uo pipefail
source "$(dirname "$0")/_lib.sh"
NAME=ingest-drain
is_disabled "$NAME" && { write_status "$NAME" "Ingest drain check" "daily 08:10" scheduled 1 "disabled"; exit 0; }

QUEUE_DB="/Volumes/AXAGON/Ahel/knowledge/private/_system/queue/queue.db"
counts=$(sqlite3 "$QUEUE_DB" \
  "select status || '=' || count(*) from queue_messages group by status;" 2>/dev/null | tr '\n' ' ')
pending=$(sqlite3 "$QUEUE_DB" \
  "select count(*) from queue_messages where status in (char(112,101,110,100,105,110,103), char(112,97,114,107,101,100), char(112,114,111,99,101,115,115,105,110,103));" 2>/dev/null)
pool_ok=0
curl -s -m 5 http://192.168.8.178:8080/health | grep -q '"ok"' && pool_ok=1

if [ -z "$counts" ]; then
  write_status "$NAME" "Ingest drain check" "daily 08:10" scheduled 0 "queue.db unreadable (AXAGON mounted?)"
  notify "Ingest drain check" "Private realm queue.db unreadable — is AXAGON mounted?"
  exit 0
fi
if [ "${pending:-0}" -gt 0 ]; then
  write_status "$NAME" "Ingest drain check" "daily 08:10" scheduled 0 \
    "${pending} items not drained (${counts}) — pool $( [ "$pool_ok" = 1 ] && echo ok || echo DOWN )"
  notify "Ingest drain incomplete" "${pending} private-realm items still queued after the 02:00 window (${counts}). Chat may be slow if the drain is still running."
else
  write_status "$NAME" "Ingest drain check" "daily 08:10" scheduled 1 \
    "queue drained (${counts:-empty}) — pool $( [ "$pool_ok" = 1 ] && echo ok || echo DOWN )"
fi
