#!/bin/bash
#
# codevibe-claude - Wrapper to run Claude Code inside tmux for mobile control
#
# This script launches Claude Code inside a tmux session, enabling:
# - Mobile prompts when screen is locked (via tmux send-keys)
# - Same user experience as regular claude command
# - Automatic session naming based on Claude session ID
#
# Usage:
#   codevibe-claude [claude-args...]
#   codevibe-claude login              # Sign in via browser
#   codevibe-claude logout             # Sign out
#   codevibe-claude status             # Show auth status
#
# Environment:
#   ENVIRONMENT                         # Set to 'production' (default) or 'development'
#
# Examples:
#   codevibe-claude                    # Start new session
#   codevibe-claude --resume           # Resume last session
#   codevibe-claude -p "fix the bug"   # Start with prompt
#   ENVIRONMENT=development codevibe-claude 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
case "$1" in
    login|logout|status|reset-device)
        # Use codevibe-core CLI
        CORE_CLI="$PLUGIN_DIR/node_modules/@quantiya/codevibe-core/bin/codevibe.js"
        if [ -f "$CORE_CLI" ]; then
            exec node "$CORE_CLI" "$1"
        else
            echo "Error: codevibe-core not found. Run 'npm install' in the plugin directory first."
            exit 1
        fi
        ;;
esac

# Check authentication before launching
CORE_CLI="$PLUGIN_DIR/node_modules/@quantiya/codevibe-core/bin/codevibe.js"
if [ -f "$CORE_CLI" ]; then
    AUTH_STATUS=$(node "$CORE_CLI" status 2>/dev/null)
    if echo "$AUTH_STATUS" | grep -q "Not authenticated"; then
        echo ""
        echo "⚠️  CodeVibe: Not authenticated."
        echo "   Run 'codevibe-claude login' to sign in first."
        echo ""
        exit 1
    fi
fi

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

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

# 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

# Generate a unique session name
SESSION_NAME="${TMUX_SESSION_PREFIX}-$$"

log "Starting codevibe-claude with session: $SESSION_NAME"
log "Arguments: $*"

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

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

# Create tmux session and run claude
# -d: detached initially so we can set up
# Then attach to it
log "Creating tmux session: $SESSION_NAME"

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

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

tmux new-session -d -s "$SESSION_NAME" -x "$(tput cols)" -y "$(tput lines)" \
    "export CODEVIBE_TMUX_SESSION='$SESSION_NAME'; export ENVIRONMENT='$ENVIRONMENT'; $CLAUDE_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 the MCP server to find
# The session-start hook will update this with the actual Claude session ID
echo "$SESSION_NAME" > "${CODEVIBE_TMPDIR}/codevibe-claude-tmux-session-$$"

log "Attaching to tmux session: $SESSION_NAME"

# Attach to the session
# This will show claude's UI to the user
exec tmux attach-session -t "$SESSION_NAME"
