#!/bin/bash
#
# Wrapper script for 'vcm auto:start' that properly handles Ctrl+C and other key presses
# This script runs vcm auto:start in the background and monitors keyboard input
#

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
GRAY='\033[0;37m'
NC='\033[0m' # No Color

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CLI_DIR="$(dirname "$SCRIPT_DIR")"

# Path to vcm command
ANA_CMD="$CLI_DIR/bin/vibecodingmachine.js"

# Path to stop file
STOP_FILE="$HOME/.config/vibecodingmachine/.stop"

# Cleanup function
cleanup() {
  echo -e "\n${YELLOW}Stopping auto mode...${NC}"

  # Create stop file to signal the process
  mkdir -p "$(dirname "$STOP_FILE")"
  echo "Stop requested at $(date)" > "$STOP_FILE"

  # Send SIGTERM to the vcm process if it's running
  if [ -n "$ANA_PID" ] && kill -0 "$ANA_PID" 2>/dev/null; then
    kill -TERM "$ANA_PID" 2>/dev/null || true
  fi

  # Wait a moment for the process to exit gracefully
  sleep 2

  # Force kill if still running
  if [ -n "$ANA_PID" ] && kill -0 "$ANA_PID" 2>/dev/null; then
    echo -e "${YELLOW}Force stopping...${NC}"
    kill -9 "$ANA_PID" 2>/dev/null || true
  fi

  # Also kill any remaining aider processes
  pkill -9 -f "aider.*vibecodingmachine" 2>/dev/null || true

  echo -e "${GREEN}Auto mode stopped${NC}"
  exit 0
}

# Set up trap for Ctrl+C
trap cleanup INT TERM

# Start vcm auto:start in background
echo -e "${GRAY}Starting auto mode...${NC}"
echo -e "${GRAY}Press Ctrl+C, Esc, or 'x' to stop${NC}"
echo ""

# Start vcm in background, saving its PID
# Set ANA_WRAPPER_RUNNING to prevent infinite recursion
export ANA_WRAPPER_RUNNING=1
node "$ANA_CMD" auto:start "$@" &
ANA_PID=$!

# Monitor for keyboard input AND stop file in the foreground
# Use a non-blocking read to check for key presses
while kill -0 "$ANA_PID" 2>/dev/null; do
  # Check for stop file first (created by 'vcm auto:stop' or Ctrl+C signal)
  if [ -f "$STOP_FILE" ]; then
    echo -e "\n${YELLOW}Stop signal detected${NC}"
    cleanup
  fi

  # Read a single character with 0.5 second timeout
  if read -t 0.5 -n 1 -s key 2>/dev/null; then
    # Check if key is 'x', Esc (ASCII 27), or Ctrl+C
    if [ "$key" = "x" ] || [ "$key" = "X" ] || [ "$(printf '%d' "'$key")" = "27" ]; then
      echo -e "\n${YELLOW}Stop key pressed${NC}"
      cleanup
    fi
  fi
done

# Process exited naturally
echo -e "\n${GREEN}Auto mode completed${NC}"
wait "$ANA_PID"
exit_code=$?
exit $exit_code
