#!/bin/bash
# Ralph MCP Logger Hook
# Logs MCP tool calls to .ralph/logs/
#
# This hook is called by Claude Code before MCP tool invocations
# when Ralph Loop is active.

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

# Configuration
RALPH_LOG_DIR=".ralph/logs"
LOG_FILE="${RALPH_LOG_DIR}/ralph-$(date +%Y-%m-%d).log"

# Ensure log directory exists
mkdir -p "$RALPH_LOG_DIR"

# Get tool info from environment (set by Claude Code)
TOOL_NAME="${CLAUDE_TOOL_NAME:-unknown}"
TOOL_PARAMS="${CLAUDE_TOOL_PARAMS:-}"

# Timestamp
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Log the MCP call
if [[ "$TOOL_NAME" == mcp__* ]]; then
  echo "[$TIMESTAMP] [MCP] Tool: $TOOL_NAME" >> "$LOG_FILE"

  # Extract MCP server name
  if [[ "$TOOL_NAME" == mcp__smartstack__* ]]; then
    echo "[$TIMESTAMP] [MCP]   Server: smartstack" >> "$LOG_FILE"
  elif [[ "$TOOL_NAME" == mcp__plugin_context7* ]]; then
    echo "[$TIMESTAMP] [MCP]   Server: context7" >> "$LOG_FILE"
  fi

  # Log params if not too long
  if [[ ${#TOOL_PARAMS} -lt 500 ]]; then
    echo "[$TIMESTAMP] [MCP]   Params: $TOOL_PARAMS" >> "$LOG_FILE"
  else
    echo "[$TIMESTAMP] [MCP]   Params: (truncated - ${#TOOL_PARAMS} chars)" >> "$LOG_FILE"
  fi
fi

exit 0
