#!/bin/bash

# Gemini CLI SessionStart hook
# Called when a Gemini session starts
#
# Input (JSON via stdin):
# {
#   "session_id": "uuid",
#   "cwd": "/current/working/directory",
#   "hook_event_name": "SessionStart",
#   "source": "startup" | "resume" | "clear",
#   ...
# }

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

log "INFO" "SessionStart hook triggered"

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

if [ -z "$INPUT" ]; then
  log "ERROR" "No input received"
  exit 0  # Exit gracefully so Gemini continues
fi

log "DEBUG" "Received input: $INPUT"

# Extract fields
SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty')
CWD=$(echo "$INPUT" | jq -r '.cwd // empty')
SOURCE=$(echo "$INPUT" | jq -r '.source // "startup"')

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

log "INFO" "Session ID: $SESSION_ID, source: $SOURCE"

# Check if MCP server is running
if ! check_mcp_server "$SESSION_ID"; then
  log "WARN" "MCP server not running, session events will not be synced"
  exit 0
fi

# Build event payload with geminiSessionId in metadata
EVENT_PAYLOAD=$(jq -n \
  --arg session_id "$SESSION_ID" \
  --arg cwd "$CWD" \
  --arg source "$SOURCE" \
  '{
    session_id: $session_id,
    hook_event_name: "SessionStart",
    type: "NOTIFICATION",
    source: "DESKTOP",
    content: "Session started via hook",
    metadata: {
      hook_event_name: "SessionStart",
      cwd: $cwd,
      source: $source,
      geminiSessionId: $session_id
    }
  }')

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

log "INFO" "SessionStart hook completed"
exit 0
