#!/bin/bash

# Last Words MCP - User Input Script
# This script opens in a new terminal to get user input

OUTPUT_FILE="$1"
CONTEXT_FILE="$2"

# Check if we're running in a terminal, if not, open one
if [ ! -t 0 ] || [ -z "$TERM" ]; then
    # Not in a terminal, try to open one
    if command -v gnome-terminal >/dev/null 2>&1; then
        gnome-terminal -- bash "$0" "$@"
        exit 0
    elif command -v xterm >/dev/null 2>&1; then
        xterm -e bash "$0" "$@"
        exit 0
    elif command -v konsole >/dev/null 2>&1; then
        konsole -e bash "$0" "$@"
        exit 0
    else
        # No terminal available, continue anyway
        echo "Warning: No terminal emulator found, running in current context"
    fi
fi

clear
echo "============================================================"
echo "🗣️  LAST WORDS - Final Input to AI Assistant"
echo "============================================================"
echo ""

# Show context if provided
if [ -f "$CONTEXT_FILE" ]; then
    echo "📝 Context from AI:"
    cat "$CONTEXT_FILE"
    echo ""
    echo "------------------------------------------------------------"
    echo ""
fi

echo "💡 This tool saves message credits by using a tool call instead of a chat message."
echo "Type your final instructions, clarifications, or additional context below."
echo "Press Enter when finished, or Ctrl+C to cancel."
echo ""

# Function to handle Ctrl+C
cleanup() {
    echo ""
    echo ""
    echo "❌ Input cancelled by user."
    echo "CANCELLED" > "$OUTPUT_FILE"
    echo "============================================================"
    exit 0
}

# Set up signal handler
trap cleanup SIGINT

# Get user input
read -p "Your message: " user_input

echo ""
if [ -n "$user_input" ]; then
    echo "✅ Message sent to AI assistant!"
    echo "$user_input" > "$OUTPUT_FILE"
else
    echo "❌ No input provided. Cancelled."
    echo "CANCELLED" > "$OUTPUT_FILE"
fi

echo "============================================================"
echo "You can close this terminal now."
echo "Window will close automatically in 3 seconds..."
sleep 3
