#!/bin/bash
# Waits for the sweep to end, writes the per-source outcome into the window entry, and tells rian.
# CLAUDE.md: a long unattended job that finishes is worth a message; routine narration is not.
set -u
D="$(cd "$(dirname "$0")" && pwd)"
WINDOW="$D/../window-2026-09-19b-sweep.md"

live() { docker exec dutyfreeprofessor-app sh -c 'for p in /proc/[0-9]*; do c=$(tr "\0" "\n" < $p/cmdline 2>/dev/null | tail -1); case "$c" in avolta*|extime*) echo x;; esac; done' 2>/dev/null | wc -l; }

sleep 300                      # let them all get going before watching for the end
until [ "$(live)" -eq 0 ]; do sleep 180; done

SUMMARY=$(docker exec dutyfreeprofessor-db psql -U dfp -d dfp -tA -F' ' -c \
  "SELECT s.slug, r.status, r.prices_written FROM collection_runs r JOIN sources s ON s.id=r.source_id
   WHERE r.started_at > now() - interval '12 hours' ORDER BY s.slug;" 2>/dev/null)
OK=$(echo "$SUMMARY" | grep -c ' ok ')
BAD=$(echo "$SUMMARY" | grep -vc ' ok ')
PRICES=$(echo "$SUMMARY" | awk '{s+=$3} END{print s+0}')
PEAK=$(awk -F'\t' 'NR>1 && $2>m {m=$2} END{print m+0}' "$D/memory-trace.tsv" 2>/dev/null)

{
  echo
  echo "## Closed $(date '+%F %H:%M') — the sweep ended"
  echo
  echo "$OK source(s) ok, $BAD not, $PRICES prices written. Peak container memory ${PEAK} MiB of the"
  echo "4096 MiB cap (the trace is \`memory-trace.tsv\`; anything shed is in \`guard.log\`)."
  echo
  echo '```'
  echo "$SUMMARY"
  echo '```'
  echo
  echo "Next: the review passes — \`/review-pass\` per \`main/docs/REVIEW-PASS.md\`, starting with"
  echo "rabanne, until \`app.cli pass status\` prints done. Staging may be deployed again."
} >> "$WINDOW"

srv-gw notify --from "DFP sweep" "Collection sweep finished: $OK ok, $BAD not, $PRICES prices. Peak container memory ${PEAK}MiB of 4096. Staging is free to deploy; review passes are next." >/dev/null 2>&1
echo "$(date '+%F %T') sweep finished: $OK ok, $BAD not, $PRICES prices, peak ${PEAK}MiB" >> "$D/guard.log"
