#!/bin/bash

# SessionEnd Hook
# Triggered when a Claude Code session ends
# Cleans up sync session and unsubscribes from mobile events

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

log "INFO" "SessionEnd hook triggered"

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

log "DEBUG" "Input: $INPUT"

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

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

EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
  log "INFO" "SessionEnd event sent successfully"

  # Clean up session-specific files
  if [ -n "$SESSION_ID" ]; then
    PID_FILE="${CODEVIBE_TMPDIR}/codevibe-claude-${SESSION_ID}.pid"
    PORT_FILE="${CODEVIBE_TMPDIR}/codevibe-claude-${SESSION_ID}.port"

    # Kill the MCP server for this session
    if [ -f "$PID_FILE" ]; then
      PID=$(cat "$PID_FILE")
      if ps -p "$PID" > /dev/null 2>&1; then
        log "INFO" "Stopping MCP server for session $SESSION_ID (PID: $PID)"
        kill "$PID" 2>/dev/null || true
      fi
      rm -f "$PID_FILE"
    fi

    # Remove port file (should also be cleaned up by server, but just in case)
    rm -f "$PORT_FILE"

    # Remove sent UUIDs tracking file
    SENT_UUIDS_FILE="${CODEVIBE_TMPDIR}/codevibe-claude-sent-uuids-${SESSION_ID}.txt"
    rm -f "$SENT_UUIDS_FILE"

    log "INFO" "Session cleanup completed for $SESSION_ID"
  fi
else
  log "ERROR" "Failed to send SessionEnd event (exit code: $EXIT_CODE)"
fi

# Hooks are best-effort telemetry. Never propagate send_to_mcp failures to
# Claude Code — a missing/unreachable daemon must not surface as a hook error.
exit 0
