#!/usr/bin/env bash
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.

function app_realpath() {
	SOURCE=$1
	while [ -h "$SOURCE" ]; do
		DIR=$(dirname "$SOURCE")
		SOURCE=$(readlink "$SOURCE")
		[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE
	done
	SOURCE_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
	echo "${SOURCE_DIR%%${SOURCE_DIR#*.app}}"
}

function fallback_to_cursor_cli() {
	if [ -n "$CURSOR_CLI" ]; then
		# Falling back to direct CLI execution
		eval "$CURSOR_CLI" "$@"
	else
		echo "Error: Neither cursor-agent nor fallback CLI found. Please install Cursor properly." 1>&2
		exit 1
	fi
}

function find_cursor_cli() {
	# Clear the output variables
	CURSOR_CLI=""
	CURSOR_CLI_MODE=""

	# when run in remote terminal, use the remote cli
	if [ -n "$VSCODE_IPC_HOOK_CLI" ]; then
		REMOTE_CLI="$(which -a 'cursor' | grep /remote-cli/)"
		if [ -n "$REMOTE_CLI" ]; then
			CURSOR_CLI="$REMOTE_CLI"
			CURSOR_CLI_MODE="remote"
			return 0
		fi
	fi

	# Otherwise, use the electron app
	APP_PATH="$(app_realpath "${BASH_SOURCE[0]}")"
	if [ -z "$APP_PATH" ]; then
		echo "Unable to determine app path from symlink : ${BASH_SOURCE[0]}" >&2
		return 1
	fi
	CONTENTS="$APP_PATH/Contents"
	ELECTRON="$CONTENTS/MacOS/Cursor"
	CLI="$CONTENTS/Resources/app/out/cli.js"
	CURSOR_CLI="ELECTRON_RUN_AS_NODE=1 \"$ELECTRON\" \"$CLI\""
	CURSOR_CLI_MODE="local"
	return 0
}

# Main execution
export VSCODE_NODE_OPTIONS=$NODE_OPTIONS
export VSCODE_NODE_REPL_EXTERNAL_MODULE=$NODE_REPL_EXTERNAL_MODULE
unset NODE_OPTIONS
unset NODE_REPL_EXTERNAL_MODULE

# If cursor-agent exists, try to find CURSOR_CLI but don't fail if we can't
if find_cursor_cli 2>/dev/null; then
	# Export both variables if we found them
	if [ -n "$CURSOR_CLI" ]; then
		export CURSOR_CLI
		export CURSOR_CLI_MODE
	fi
fi

if [ "$CURSOR_CLI_BLOCK_CURSOR_AGENT" = "true" ]; then
  # cursor-agent is forbidden, call cursor CLI directly
	fallback_to_cursor_cli "$@"
fi

AGENT_JUST_INSTALLED=false
if ! command -v ~/.local/bin/cursor-agent >/dev/null 2>&1; then
	echo "cursor-agent not found, installing via https://cursor.com/install ..."
	curl -sS https://cursor.com/install | bash >/dev/null 2>&1
	# Remove the previous log line from the terminal output
	tput cuu1 && tput el
	AGENT_JUST_INSTALLED=true
fi

# Check current cursor-agent version meets minimum version requirement
# If it fails with exit code 2 (version too old), update and retry
OUTPUT=$({ ~/.local/bin/cursor-agent --min-version=2025.09.04 status; } 2>&1)
EXIT_CODE=$?

# Update and retry if cursor was not just installed and:
#  - exit code is 2 (version too old), OR
#  - exit code is 1 and output contains "unknown option" (old agent CLI version doesn't have the --min-version option)
if { [ "$EXIT_CODE" -eq 2 ] || { [ "$EXIT_CODE" -eq 1 ] && echo "$OUTPUT" | grep -qi "unknown option"; }; }; then
	echo "cursor-agent version is outdated, updating..."
	~/.local/bin/cursor-agent update >/dev/null 2>&1
	# Remove the previous log line from the terminal output
	tput cuu1 && tput el
	# Check new version to see if minimum version requirement is met
	OUTPUT2=$({ ~/.local/bin/cursor-agent --min-version=2025.09.04 status; } 2>&1)
	EXIT_CODE2=$?
	if { [ "$EXIT_CODE2" -eq 2 ] || { [ "$EXIT_CODE2" -eq 1 ] && echo "$OUTPUT2" | grep -qi "unknown option"; }; }; then
		# If the second attempt also fails, just try CURSOR_CLI as a fallback
		fallback_to_cursor_cli "$@"
	else
		# min-version is met, run cursor-agent
		export CURSOR_CLI_COMPAT=1
		exec ~/.local/bin/cursor-agent "$@"
	fi
else
	# min-version is met, run cursor-agent
	export CURSOR_CLI_COMPAT=1
	exec ~/.local/bin/cursor-agent "$@"
fi
