#!/bin/bash
#
# codevibe-gemini - Wrapper to run Gemini CLI inside tmux for mobile control
#
# This script launches Gemini CLI inside a tmux session, enabling:
# - Mobile prompts when screen is locked (via tmux send-keys)
# - Same user experience as regular gemini command
# - Automatic sync with iOS app via MCP server
#
# Usage:
#   codevibe-gemini [gemini-args...]
#   codevibe-gemini login              # Sign in via browser
#   codevibe-gemini logout             # Sign out
#   codevibe-gemini status             # Show auth status
#
# Environment:
#   ENVIRONMENT                         # Set to 'production' (default) or 'development'
#
# Examples:
#   codevibe-gemini                    # Start new session
#   codevibe-gemini --resume           # Resume last session
#   codevibe-gemini "fix the bug"      # Start with prompt
#   ENVIRONMENT=development codevibe-gemini login  # Login to development
#

set -e

# Default to production environment if not specified
# Users can set ENVIRONMENT=development for local development
export ENVIRONMENT="${ENVIRONMENT:-production}"

# Use TMPDIR if set (macOS sets this to user-specific temp), otherwise /tmp
CODEVIBE_TMPDIR="${TMPDIR:-/tmp}"

# Get the directory where this script is located (resolving symlinks)
# This is needed because npm global installs symlink bin scripts to /usr/local/bin/
SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
PLUGIN_DIR="$(dirname "$SCRIPT_DIR")"

# Handle auth commands (login, logout, status, reset-device)
# Delegate to codevibe-core CLI (shared auth across all plugins)
case "$1" in
    login|logout|status|reset-device)
        CORE_CLI="$PLUGIN_DIR/node_modules/@quantiya/codevibe-core/bin/codevibe.js"
        # Also check hoisted location (when installed via @quantiya/codevibe meta-package)
        if [ ! -f "$CORE_CLI" ]; then
            CORE_CLI="$PLUGIN_DIR/../codevibe-core/bin/codevibe.js"
        fi
        if [ -f "$CORE_CLI" ]; then
            exec node "$CORE_CLI" "$1"
        else
            echo "Error: codevibe-core not found. Try reinstalling: npm install -g @quantiya/codevibe"
            exit 1
        fi
        ;;
esac

# Export hooks directory for hook scripts to use
export CODEVIBE_HOOKS_DIR="$PLUGIN_DIR/hooks"

# Auto-configure hooks on startup if not already configured
configure_hooks_if_needed() {
    GEMINI_SETTINGS_DIR="$HOME/.gemini"
    GEMINI_SETTINGS_FILE="$GEMINI_SETTINGS_DIR/settings.json"
    HOOKS_DIR="$PLUGIN_DIR/hooks"
    TEMPLATE_FILE="$PLUGIN_DIR/gemini-hooks-settings.json"

    # Make hook scripts executable
    chmod +x "$HOOKS_DIR"/*.sh 2>/dev/null || true

    # Create .gemini directory if it doesn't exist
    mkdir -p "$GEMINI_SETTINGS_DIR"

    # Check if hooks need to be configured
    if [ ! -f "$GEMINI_SETTINGS_FILE" ]; then
        # No settings file - create it with hooks
        echo "Configuring Gemini CLI hooks for CodeVibe..."
        sed "s|__CODEVIBE_HOOKS_DIR__|$HOOKS_DIR|g" "$TEMPLATE_FILE" > "$GEMINI_SETTINGS_FILE"
        echo "✓ Hooks configured at: $GEMINI_SETTINGS_FILE"
    elif ! grep -q "BeforeAgent" "$GEMINI_SETTINGS_FILE" 2>/dev/null; then
        # Settings file exists but missing agent hooks - warn user to upgrade
        echo "⚠ Gemini CLI hooks need updating. BeforeAgent/AfterAgent hooks required."
        echo "  Update hooks in: $GEMINI_SETTINGS_FILE"
        echo "  Or delete the file and restart to auto-configure."
        echo ""
    elif ! grep -q "BeforeTool" "$GEMINI_SETTINGS_FILE" 2>/dev/null; then
        # Settings file exists but no tool hooks - warn user
        echo "⚠ Gemini CLI hooks not fully configured."
        echo "  To enable interactive prompts from mobile, add hooks to:"
        echo "  $GEMINI_SETTINGS_FILE"
        echo ""
    fi
}

# Configure hooks before starting
configure_hooks_if_needed

# Configuration
TMUX_SESSION_PREFIX="codevibe-gemini"
LOG_FILE="${CODEVIBE_TMPDIR}/codevibe-gemini-wrapper.log"
MCP_LOG_FILE="${CODEVIBE_TMPDIR}/codevibe-gemini-mcp.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
}

# Cleanup function to kill MCP server when wrapper exits
cleanup() {
    log "Cleanup triggered"
    if [ -n "$MCP_PID" ] && kill -0 "$MCP_PID" 2>/dev/null; then
        log "Stopping MCP server (PID: $MCP_PID)"
        kill "$MCP_PID" 2>/dev/null || true
        wait "$MCP_PID" 2>/dev/null || true
    fi
    # Remove PID file
    rm -f "${CODEVIBE_TMPDIR}/codevibe-gemini-mcp-$$.pid"
}

# Set up trap for cleanup
trap cleanup EXIT INT TERM

# Check if tmux is installed
if ! command -v tmux &> /dev/null; then
    echo "Error: tmux is required but not installed."
    echo "Install with: brew install tmux"
    exit 1
fi

# Check if gemini is installed
if ! command -v gemini &> /dev/null; then
    echo "Error: gemini CLI is not installed."
    echo "Install from: https://github.com/google-gemini/gemini-cli"
    exit 1
fi

# Check if node is installed
if ! command -v node &> /dev/null; then
    echo "Error: Node.js is required but not installed."
    exit 1
fi

# Check if MCP server is built
if [ ! -f "$PLUGIN_DIR/dist/server.js" ]; then
    echo "Error: MCP server not built. Run 'npm run build' in the plugin directory first."
    exit 1
fi

# Generate a unique session name
SESSION_NAME="${TMUX_SESSION_PREFIX}-$$"
WORKING_DIR="$(pwd)"

log "Starting codevibe-gemini with session: $SESSION_NAME"
log "Working directory: $WORKING_DIR"
log "Arguments: $*"

# Check if we're already inside tmux
if [ -n "$TMUX" ]; then
    log "Already inside tmux, running gemini directly"
    # Already in tmux, just run gemini
    exec gemini "$@"
fi

# Check if running in a terminal
if [ ! -t 0 ] || [ ! -t 1 ]; then
    log "Not running in a terminal, running gemini directly"
    exec gemini "$@"
fi

# Start MCP server in background BEFORE launching Gemini
# The MCP server will watch the transcript file for changes
log "Starting MCP server..."
export GEMINI_WORKING_DIRECTORY="$WORKING_DIR"
export CODEVIBE_GEMINI_TMUX_SESSION="$SESSION_NAME"

# Start MCP server and capture its PID
node "$PLUGIN_DIR/dist/server.js" >> "$MCP_LOG_FILE" 2>&1 &
MCP_PID=$!
echo "$MCP_PID" > "${CODEVIBE_TMPDIR}/codevibe-gemini-mcp-$$.pid"

log "MCP server started with PID: $MCP_PID"

# Wait a moment for MCP server to initialize
sleep 1

# Check if MCP server is still running (exits if auth failed)
if ! kill -0 "$MCP_PID" 2>/dev/null; then
    log "ERROR: MCP server failed to start"
    # Show the last few lines of the log for context (e.g., auth error)
    echo ""
    tail -3 "$MCP_LOG_FILE" 2>/dev/null | grep -v '^\[' | head -1
    echo ""
    echo "Server failed to start. Check $MCP_LOG_FILE for details."
    exit 1
fi

# Create tmux session and run gemini
log "Creating tmux session: $SESSION_NAME"

# Build the gemini command with proper escaping
GEMINI_CMD="gemini"
for arg in "$@"; do
    # Escape single quotes in arguments
    escaped_arg=$(printf '%s' "$arg" | sed "s/'/'\\\\''/g")
    GEMINI_CMD="$GEMINI_CMD '$escaped_arg'"
done

# Create the session running gemini, then attach
# We use a wrapper that:
# 1. Exports the session name so prompts can find it
# 2. Runs gemini
# 3. Exits the tmux session when gemini exits

tmux new-session -d -s "$SESSION_NAME" -x "$(tput cols)" -y "$(tput lines)" \
    "export CODEVIBE_GEMINI_TMUX_SESSION='$SESSION_NAME'; export ENVIRONMENT='$ENVIRONMENT'; $GEMINI_CMD; exit"

# Enable mouse support for scrolling
tmux set-option -t "$SESSION_NAME" -g mouse on

# Enable copy/paste with system clipboard (macOS)
tmux set-option -t "$SESSION_NAME" set-clipboard on
tmux set-window-option -t "$SESSION_NAME" mode-keys vi
tmux bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy"
tmux bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel "pbcopy"

# Store session mapping for mobile prompts
echo "$SESSION_NAME" > "${CODEVIBE_TMPDIR}/codevibe-gemini-tmux-session-$$"

log "Attaching to tmux session: $SESSION_NAME"

# Attach to the session
# This will show gemini's UI to the user
# When tmux session exits, the trap will clean up the MCP server
tmux attach-session -t "$SESSION_NAME"

# After tmux exits, cleanup is handled by trap
log "Tmux session ended"
