#!/bin/bash

# PostToolUse Hook
# Triggered after Claude uses a tool (Read, Edit, Write, etc.)
# Captures tool usage and file changes

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

log "INFO" "PostToolUse hook triggered"

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

log "DEBUG" "Input: $INPUT"

# Extract tool name to check if it's a file operation
TOOL_NAME=$(echo "$INPUT" | grep -o '"tool_name"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/"tool_name"[[:space:]]*:[[:space:]]*"\([^"]*\)"/\1/')

log "DEBUG" "Tool name: $TOOL_NAME"

# Extract session ID for dynamic port lookup
SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty')

# Send tool use event to MCP server
send_to_mcp "event" "$INPUT" "$SESSION_ID"
EVENT_EXIT_CODE=$?

if [ $EVENT_EXIT_CODE -eq 0 ]; then
  log "INFO" "PostToolUse event sent successfully"
else
  log "ERROR" "Failed to send PostToolUse event (exit code: $EVENT_EXIT_CODE)"
fi

# Note: File operations (Read, Edit, Write) are already captured in the TOOL_USE event above
# The tool_input and tool_response contain all necessary information including file paths and diffs
# iOS app can filter TOOL_USE events to display file changes

log "DEBUG" "PostToolUse event processing completed"

exit $EVENT_EXIT_CODE
