#!/usr/bin/env bash
# tools/today/collect.sh
#
# Aggregates "what happened in the last N hours" across the F∆I
# monorepos into a single plain-text summary the proposer feeds
# to the System-AI.
#
# Touches only git history and the bundled store-index seed file.
# Does not read the audit log without --with-audit.
set -euo pipefail

SINCE="${FAI_TODAY_SINCE:-24 hours ago}"

# Walk every fai-* directory next to fai_studio so the collector
# works from any of the sibling checkouts. Adjust here if the
# layout ever changes.
ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"

emit_section() {
  printf '\n## %s\n\n' "$1"
}

emit_section "RECENT COMMITS (last: $SINCE)"
for repo in "$ROOT"/fai_*/; do
  [ -d "$repo/.git" ] || continue
  name="$(basename "$repo")"
  log=$(git -C "$repo" log --since="$SINCE" --pretty='%h %s' 2>/dev/null || true)
  if [ -n "$log" ]; then
    printf '### %s\n%s\n\n' "$name" "$log"
  fi
done

emit_section "STORE INDEX SEED CHANGES"
seed="$ROOT/fai_platform/crates/fai_hub/store-index/seed.yaml"
if [ -f "$seed" ] && [ -d "$ROOT/fai_platform/.git" ]; then
  diff=$(git -C "$ROOT/fai_platform" log --since="$SINCE" --oneline -- \
    crates/fai_hub/store-index/seed.yaml 2>/dev/null || true)
  if [ -n "$diff" ]; then
    printf '%s\n' "$diff"
  else
    printf '(no changes in window)\n'
  fi
fi

emit_section "ARCHITECTURE / SYSTEM-GAPS CHANGES"
arch_dir="$ROOT/fai_platform/docs"
if [ -d "$arch_dir" ] && [ -d "$ROOT/fai_platform/.git" ]; then
  changes=$(git -C "$ROOT/fai_platform" log --since="$SINCE" --oneline -- \
    docs/architecture docs/advanced 2>/dev/null || true)
  if [ -n "$changes" ]; then
    printf '%s\n' "$changes"
  else
    printf '(no changes in window)\n'
  fi
fi

emit_section "STUDIO RECENT RELEASES"
studio="$ROOT/fai_studio"
if [ -d "$studio/.git" ]; then
  tags=$(git -C "$studio" log --since="$SINCE" --pretty='%h %s' \
    --grep='^feat(studio)\|^chore(studio): bump' 2>/dev/null || true)
  if [ -n "$tags" ]; then
    printf '%s\n' "$tags"
  else
    printf '(no Studio release activity)\n'
  fi
fi

emit_section "AUDIT-LOG HIGHLIGHTS"
if [ "${FAI_TODAY_WITH_AUDIT:-0}" = "1" ] && command -v fai >/dev/null 2>&1; then
  fai audit recent --limit 20 2>/dev/null | head -40 || \
    printf '(audit query failed; daemon may be stopped)\n'
else
  printf '(audit pull disabled — set FAI_TODAY_WITH_AUDIT=1 to opt in)\n'
fi
