#!/bin/bash

# BeforeAgent Hook
# Triggered when user submits a prompt in Gemini CLI
# Captures user prompts and sends to mobile app as USER_PROMPT events

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

log "INFO" "BeforeAgent hook triggered"

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

log "DEBUG" "Input: $INPUT"

# Extract fields from hook input
SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty')
PROMPT=$(echo "$INPUT" | jq -r '.prompt // empty')

# Build explicit event payload with type and content
EVENT_PAYLOAD=$(jq -n \
  --arg session_id "$SESSION_ID" \
  --arg content "$PROMPT" \
  --arg hook_event_name "BeforeAgent" \
  --arg type "USER_PROMPT" \
  '{
    session_id: $session_id,
    hook_event_name: $hook_event_name,
    type: $type,
    content: $content
  }')

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

if [ $? -eq 0 ]; then
  log "INFO" "BeforeAgent event sent successfully"
else
  log "ERROR" "Failed to send BeforeAgent event"
fi

# Always exit 0 so Gemini CLI continues normally
exit 0
