#!/usr/bin/env bash
# MindFile SessionEnd hook (capture).
#
# Runs once when a Claude Code session ends, not on every turn (it used to be a
# Stop hook, which fired after each assistant response and cost a model call each
# time). Claude Code passes hook input as JSON on stdin, including `transcript_path`.
# We hand that transcript to the hosted capture function, which checks the
# opt-in server-side, scrubs secrets, and distils 0-3 candidate patterns. The
# raw transcript is used for extraction only and deleted after 30 days.
# Installed by `npx mindfile connect`. Silent and non-blocking on every path.
set -euo pipefail

API="${MINDFILE_API_URL:-https://kvrwtxjayijgkamfnavy.supabase.co}"
ANON="${MINDFILE_ANON_KEY:-sb_publishable_SBJEnASHDeH9N3yqsUSL5Q_YNTps6Yc}"

TOKEN="$(security find-generic-password -s mindfile-token -w 2>/dev/null || cat "$HOME/.mindfile/token" 2>/dev/null || true)"
[ -n "$TOKEN" ] || exit 0

# Read the hook payload from stdin and find the transcript path.
INPUT="$(cat || true)"
TRANSCRIPT="$(printf '%s' "$INPUT" | jq -r '.transcript_path // empty' 2>/dev/null || true)"
[ -n "$TRANSCRIPT" ] && [ -f "$TRANSCRIPT" ] || exit 0

curl -fsS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "apikey: ${ANON}" \
  -H "Content-Type: application/json" \
  --data-binary @<(jq -Rs '{transcript: .}' < "$TRANSCRIPT") \
  "${API}/functions/v1/pattern-capture-session" >/dev/null 2>&1 \
  || true
