#!/bin/bash
# Ralph Session End Hook
# Generates a session summary when Ralph loop ends
#
# This hook is called when Claude Code session stops
# and Ralph was active.

# Check if Ralph was active
if [[ -z "$RALPH_STARTED" ]] || [[ -z "$RALPH_SESSION_ID" ]]; then
  exit 0
fi

# Configuration
RALPH_DIR=".ralph"
RALPH_LOG_DIR="${RALPH_DIR}/logs"
RALPH_REPORTS_DIR="${RALPH_DIR}/reports"
SESSION_LOG="${RALPH_LOG_DIR}/ralph-session-${RALPH_SESSION_ID}.log"

# Ensure directories exist
mkdir -p "$RALPH_REPORTS_DIR"

# Get session info
SESSION_END=$(date '+%Y-%m-%d %H:%M:%S')
PROMPT="${RALPH_PROMPT:-Unknown task}"

# Count MCP calls from log
MCP_CALLS=0
SMARTSTACK_CALLS=0
CONTEXT7_CALLS=0

if [[ -f "$SESSION_LOG" ]]; then
  MCP_CALLS=$(grep -c '\[MCP\] Tool:' "$SESSION_LOG" 2>/dev/null || echo 0)
  SMARTSTACK_CALLS=$(grep -c 'Server: smartstack' "$SESSION_LOG" 2>/dev/null || echo 0)
  CONTEXT7_CALLS=$(grep -c 'Server: context7' "$SESSION_LOG" 2>/dev/null || echo 0)
fi

# Generate session report
REPORT_FILE="${RALPH_REPORTS_DIR}/session-${RALPH_SESSION_ID}.md"

cat > "$REPORT_FILE" << EOF
# Ralph Session Report

## Session Info
- **Session ID**: ${RALPH_SESSION_ID}
- **End Time**: ${SESSION_END}
- **Task**: ${PROMPT}

## MCP Usage Summary
| Server | Calls |
|--------|-------|
| SmartStack | ${SMARTSTACK_CALLS} |
| Context7 | ${CONTEXT7_CALLS} |
| **Total** | **${MCP_CALLS}** |

## Session Log
See: \`${SESSION_LOG}\`

---
*Auto-generated by Ralph Weegund*
EOF

echo "[Ralph] Session report generated: $REPORT_FILE"

# Log session end
echo "" >> "$SESSION_LOG"
echo "# Session ended: $SESSION_END" >> "$SESSION_LOG"
echo "# MCP Calls: $MCP_CALLS (SmartStack: $SMARTSTACK_CALLS, Context7: $CONTEXT7_CALLS)" >> "$SESSION_LOG"

exit 0
