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

set -e

# Default to production environment if not specified
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

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

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

# Cleanup function to kill server when wrapper exits
cleanup() {
    log "Cleanup triggered"
    if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
        log "Stopping server (PID: $SERVER_PID)"
        kill "$SERVER_PID" 2>/dev/null || true
        wait "$SERVER_PID" 2>/dev/null || true
    fi
    # Remove PID file
    rm -f "${CODEVIBE_TMPDIR}/codevibe-codex-server-$$.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 codex is installed
if ! command -v codex &> /dev/null; then
    echo "Error: codex CLI is not installed."
    echo "Install with: npm install -g @openai/codex"
    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 server is built
if [ ! -f "$PLUGIN_DIR/dist/server.js" ]; then
    echo "Error: 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-codex 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 codex directly"
    exec codex "$@"
fi

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

# Start the session log watcher server in background
log "Starting session log watcher server..."
export CODEX_WORKING_DIRECTORY="$WORKING_DIR"
export CODEVIBE_CODEX_TMUX_SESSION="$SESSION_NAME"

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

log "Server started with PID: $SERVER_PID"

# Wait a moment for server to initialize
sleep 1

# Check if server is still running (exits if auth failed)
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
    log "ERROR: 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 codex
log "Creating tmux session: $SESSION_NAME"

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

# Create the session running codex
tmux new-session -d -s "$SESSION_NAME" -x "$(tput cols)" -y "$(tput lines)" \
    "export CODEVIBE_CODEX_TMUX_SESSION='$SESSION_NAME'; export ENVIRONMENT='$ENVIRONMENT'; $CODEX_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-codex-tmux-session-$$"

log "Attaching to tmux session: $SESSION_NAME"

# Attach to the session
tmux attach-session -t "$SESSION_NAME"

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