#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
KNOW="$ROOT/knowledge"
OUT="$KNOW/index.tsv"

mkdir -p "$KNOW"

# Keep a lightweight TSV index for quick local inspection
echo -e "path\tmtime\theadline" > "$OUT"

find "$KNOW" -type f -name "*.md" | while read -r f; do
  rel="${f#$ROOT/}"
  mtime="$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$f" 2>/dev/null || echo "")"
  headln="$(grep -m1 -E '^#' "$f" | sed 's/^#\+\s*//' || true)"
  echo -e "${rel}\t${mtime}\t${headln}" >> "$OUT"
done

echo "Wrote $OUT"

# If qmd is installed, refresh all registered collections
if command -v qmd >/dev/null 2>&1; then
  qmd update >/dev/null || true
  echo "qmd collections updated"
fi
