#!/bin/bash

# Gemini CLI AfterTool hook
# Called after a tool is executed - captures tool results
#
# Input (JSON via stdin):
# {
#   "session_id": "uuid",
#   "hook_event_name": "AfterTool",
#   "tool_name": "shell" | "edit" | "write" | etc,
#   "tool_input": { ... tool-specific input ... },
#   "tool_response": { ... tool output/result ... },
#   ...
# }

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

log "INFO" "AfterTool 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 fields
SESSION_ID=$(echo "$INPUT" | grep -o '"session_id"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/')
TOOL_NAME=$(echo "$INPUT" | grep -o '"tool_name"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/')

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

log "INFO" "Session: $SESSION_ID, Tool: $TOOL_NAME"

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

# Build event payload with the full hook input
# The server will extract tool_input and tool_response
EVENT_PAYLOAD=$(cat <<PAYLOAD
{
  "session_id": "$SESSION_ID",
  "hook_event_name": "AfterTool",
  "type": "TOOL_USE",
  "source": "DESKTOP",
  "content": "Tool executed: $TOOL_NAME",
  "metadata": {
    "hook_event_name": "AfterTool",
    "tool_name": "$TOOL_NAME",
    "hookInput": $INPUT
  }
}
PAYLOAD
)

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

log "INFO" "AfterTool hook completed"
exit 0
