#!/bin/bash
# Daily AI fleet digest — gathers live state, asks the 35B for a short brief,
# pushes to ntfy. Read-only; never changes fleet state.
set -uo pipefail
source "$(dirname "$0")/_lib.sh"
NAME=fleet-digest
is_disabled "$NAME" && { write_status "$NAME" "Fleet digest" "daily 08:00" scheduled 1 "disabled"; exit 0; }

GEN=$(promq 'llamacpp:predicted_tokens_seconds')
UP=$(promq 'count(up==1)'); TOTAL=$(promq 'count(up)')
FIRING=$(promq 'count(ALERTS{alertstate="firing"}) or vector(0)')
VAULT=$(promq '100*(1 - node_filesystem_avail_bytes{node="m1",mountpoint="/Users/admin/nas"} / node_filesystem_size_bytes{node="m1",mountpoint="/Users/admin/nas"})')
THERMAL=$(promq 'max(erebor_thermal_pressure)')
NASTEMP=$(promq 'nas_temp_celsius')

FACTS="Pool gen ${GEN:-?} tok/s. Targets up ${UP:-?}/${TOTAL:-?}. Firing alerts ${FIRING:-0}. Vault disk ${VAULT:-?}% full. Max thermal pressure ${THERMAL:-0} (0=nominal). NAS temp ${NASTEMP:-?}C."

export PROMPT="You are Ahel, the operator's private fleet AI. Given these live facts, write a 3-5 line morning brief: state overall health in one line, then only what actually deserves attention (rising disk, heat, alerts, or slow pool). Be concise and specific. No preamble. Facts: $FACTS"

BODY=$(python3 - <<'PY'
import json, os
print(json.dumps({
  "model": "ahel-pool/qwen3.6-35b-heretic",
  "messages": [{"role": "user", "content": os.environ["PROMPT"]}],
  "max_tokens": 300, "temperature": 0.4,
}))
PY
)
REPLY=$(curl -s --max-time 120 "$BIFROST/chat/completions" -H 'Content-Type: application/json' -d "$BODY" \
  | python3 -c "import json,sys
try: print(json.load(sys.stdin)['choices'][0]['message']['content'].strip())
except Exception: print('')" 2>/dev/null)

if [ -z "$REPLY" ]; then
  notify "Ahel digest (raw)" "$FACTS"
  write_status "$NAME" "Fleet digest" "daily 08:00" scheduled 0 "pool unreachable — sent raw facts"
  exit 1
fi
notify "🏔 Ahel fleet digest" "$REPLY"
write_status "$NAME" "Fleet digest" "daily 08:00" scheduled 1 "$(echo "$REPLY" | head -1)"
