#!/bin/bash

# Gemini CLI SessionEnd hook
# Called when a Gemini session ends
#
# Input (JSON via stdin):
# {
#   "session_id": "uuid",
#   "hook_event_name": "SessionEnd",
#   "reason": "user_exit" | "error" | etc,
#   ...
# }

# Get script directory and source common utilities
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"

log "INFO" "SessionEnd hook triggered"

# Read JSON input from stdin
INPUT=$(read_json_input)

if [ -z "$INPUT" ]; then
  log "ERROR" "No input received"
  exit 0
fi

log "DEBUG" "Received input: $INPUT"

# Extract session_id
SESSION_ID=$(echo "$INPUT" | grep -o '"session_id"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/')

if [ -z "$SESSION_ID" ]; then
  log "ERROR" "No session_id in input"
  exit 0
fi

# Extract reason if available
REASON=$(echo "$INPUT" | grep -o '"reason"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/')
REASON="${REASON:-unknown}"

log "INFO" "Session ID: $SESSION_ID, Reason: $REASON"

# Check if MCP server is running
if ! check_mcp_server "$SESSION_ID"; then
  log "WARN" "MCP server not running, cannot send SessionEnd"
  exit 0
fi

# Build event payload
EVENT_PAYLOAD=$(cat <<PAYLOAD
{
  "session_id": "$SESSION_ID",
  "hook_event_name": "SessionEnd",
  "type": "NOTIFICATION",
  "source": "DESKTOP",
  "content": "Session ended: $REASON",
  "metadata": {
    "hook_event_name": "SessionEnd",
    "reason": "$REASON"
  }
}
PAYLOAD
)

# Send to MCP server
send_to_mcp "event" "$EVENT_PAYLOAD" "$SESSION_ID"

log "INFO" "SessionEnd hook completed"
exit 0
