#!/usr/bin/env bash
#
# Copyright (c) ApyHub
# Voiden CLI launcher for macOS and Linux

# ============================================
# VERSION - Replaced at build time by forge.config.ts
# ============================================
VOIDEN_VERSION="2.4.1-beta.1"

# Show version
show_version() {
    echo "Voiden v$VOIDEN_VERSION"
}

# Show help
show_help() {
    echo "Voiden - File and Directory Management"
    echo ""
    echo "Usage: voiden [options] or voiden path"
    echo ""
    echo "Options:"
    echo "  -v, --version     Show version information"
    echo "  -h, --help        Show this help message"
    echo "  path            Open file or directory"
    echo ""
    echo "Examples:"
    echo "  voiden                     # Open Voiden"
    echo "  voiden ~/Documents         # Open Documents directory"
    echo "  voiden myproject           # Open myproject from current directory"
    echo "  voiden file.txt  # Open files as tabs"
    echo "  voiden -v                  # Show version"
    echo "  voiden --version           # Show version"
    echo "  voiden -h                  # Show this help"
    echo "  voiden --help              # Show this help"
    echo ""
    echo "Note: Relative paths are resolved from your current terminal location"
}

# Show error for unrecognized flags
show_flag_error() {
    echo "Error: Unrecognized flag '$1'"
    echo "For information, type: voiden --help"
    exit 1
}

# Check and validate arguments
validate_arguments() {
    for arg in "$@"; do
        # Check if it's a flag (starts with -)
        if [[ "$arg" =~ ^- ]]; then
            # Check for valid flags
            case "$arg" in
                -v|--version|-h|--help)
                    # Valid flags, will be handled separately
                    ;;
                -*)
                    # Invalid flag - show error and exit
                    show_flag_error "$arg"
                    ;;
            esac
        fi
    done
}

# Resolve path based on whether it's absolute or relative
resolve_path() {
    local path="$1"
    
    # Check if path is absolute (starts with / or ~)
    if [[ "$path" == /* ]] || [[ "$path" == ~* ]]; then
        # Absolute path - expand ~ if present and return as-is
        echo "${path/#\~/$HOME}"
    elif [[ "$path" == "." ]]; then
        # Current directory - return PWD
        echo "$PWD"
    else
        # Relative path - resolve with PWD
        echo "$PWD/$path"
    fi
}

# Resolves this script's own symlink chain (e.g. /usr/local/bin/voiden, the
# CLI installer's symlink — see cliInstaller.ts's getTargetPath()) down to the
# real, packaged bin/voiden file, and returns the real directory containing
# it (bundled via extraResource — see forge.config.ts — so this is always
# <resourcesPath>/bin, on every platform).
function resolve_script_dir() {
    SOURCE=$1
    while [ -h "$SOURCE" ]; do
        DIR=$(dirname "$SOURCE")
        SOURCE=$(readlink "$SOURCE")
        [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE
    done
    cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd
}

# macOS-only: trims .../Voiden.app/Contents/Resources/bin back to the .app
# bundle root itself (.../Voiden.app), which is what the Darwin launch branch
# below expects APP_PATH to be. Was previously applied unconditionally
# inside app_realpath() (this function's old name/shape) — on a Linux path,
# which never contains ".app" anywhere, `${SOURCE_DIR#*.app}` is a no-op
# (returns the string unchanged since the pattern never matches), which then
# made `${SOURCE_DIR%%<that unchanged string>}` strip the ENTIRE path as a
# self-match, always yielding an empty APP_PATH on Linux. That silently sent
# every Linux invocation (including `agent`/`run`/`mcp-stdio`) into the
# generic-guess fallback below, which hardcodes /usr/bin as the very first
# candidate — a directory that exists on every Linux system regardless of
# where Voiden actually is — so APP_PATH was always wrong on Linux, and
# mcp-stdio always failed to find its own CLI_JS bundle as a result.
function trim_to_app_bundle() {
    local dir="$1"
    echo "${dir%%${dir#*.app}}"
}

# ============================================
# MAIN SCRIPT EXECUTION
# ============================================

# Check for help/version flags first (before validation)
for arg in "$@"; do
    case "$arg" in
        -v|--version)
            show_version
            exit 0
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
    esac
done

# `agent`/`run`/`mcp-stdio` are bundled CLI subcommands (see voiden-cli.ts),
# dispatched straight into the Node CLI further below — they have their own
# flags (e.g. `agent --claude`) that this launcher's GUI-path flag validation
# doesn't know about, so skip it for them.
case "$1" in
    agent|run|mcp-stdio)
        IS_CLI_SUBCOMMAND=1
        ;;
esac

# Validate all arguments (will exit if invalid flags found)
if [ -z "$IS_CLI_SUBCOMMAND" ]; then
    validate_arguments "$@"
fi

# Determine the application path. SCRIPT_DIR is always <resourcesPath>/bin
# on every platform (see resolve_script_dir's own comment); what counts as
# the "app path" from there is platform-specific.
SCRIPT_DIR="$(resolve_script_dir "${BASH_SOURCE[0]}")"
if [ "$(uname)" == "Darwin" ]; then
    # .../Voiden.app/Contents/Resources/bin -> .../Voiden.app
    APP_PATH="$(trim_to_app_bundle "$SCRIPT_DIR")"
else
    # .../resources/bin -> up two levels -> the install prefix itself
    # (matches this script's own Linux launch branch below, which expects
    # the main binary directly at $APP_PATH and resources/ under it).
    APP_PATH="$(dirname "$(dirname "$SCRIPT_DIR")")"
fi

# If we couldn't determine it from the symlink chain (e.g. this script was
# copied/invoked directly rather than through the installed symlink), fall
# back to guessing a common installation path. Checked in order of
# specificity — /usr/bin exists on every Linux system regardless of where
# Voiden actually is, so it must be checked last, not first, or it always
# wins and every other candidate becomes unreachable.
if [ -z "$APP_PATH" ] || [ ! -d "$APP_PATH" ]; then
    if [ "$(uname)" == "Darwin" ]; then
        APP_PATH="/Applications/Voiden.app"
    else
        if [ -d "/opt/Voiden" ]; then
            APP_PATH="/opt/Voiden"
        elif [ -d "/usr/share/voiden" ]; then
            APP_PATH="/usr/share/voiden"
        elif [ -d "$HOME/.local/share/voiden" ]; then
            APP_PATH="$HOME/.local/share/voiden"
        elif [ -d "/usr/bin" ]; then
            APP_PATH="/usr/bin"
        fi
    fi
fi

# Verify app path exists
if [ ! -d "$APP_PATH" ]; then
	echo "Unable to find Voiden installation"
    echo "Searched: $APP_PATH"
    exit 1
fi

# Launch based on platform
if [ "$(uname)" == "Darwin" ]; then
	# macOS
    ELECTRON="$APP_PATH/Contents/MacOS/Voiden"
    if [ ! -f "$ELECTRON" ]; then
		echo "Voiden executable not found at: $ELECTRON"
        exit 1
    fi

    # `agent`/`run`/`mcp-stdio`: run the bundled CLI (inside app.asar, next to
    # main.js — see voiden-cli.ts's own doc comment) as plain Node via the
    # packaged Electron binary's ELECTRON_RUN_AS_NODE mode, instead of
    # falling through to "open this as a GUI file/folder path" below. `exec`
    # replaces this script so stdin/stdout stay directly connected — required
    # for `mcp-stdio`, which speaks the MCP protocol over them.
    if [ -n "$IS_CLI_SUBCOMMAND" ]; then
        CLI_JS="$APP_PATH/Contents/Resources/app.asar/.vite/build/voiden-cli.js"
        exec env ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI_JS" "$@"
    fi

    # Process arguments and resolve paths
    RESOLVED_ARGS=()
    
    for arg in "$@"; do
        # Skip flags (they were already handled)
        if [[ "$arg" =~ ^- ]]; then
            continue
        fi
        
        # Resolve the path
        resolved_path=$(resolve_path "$arg")
        RESOLVED_ARGS+=("$resolved_path")
    done

    # Launch detached from terminal with proper argument passing
    if [ ${#RESOLVED_ARGS[@]} -eq 0 ]; then
        # No arguments, just open the app
        nohup "$ELECTRON" > /dev/null 2>&1 &
    else
        # Pass resolved arguments directly, detached
        nohup "$ELECTRON" "${RESOLVED_ARGS[@]}" > /dev/null 2>&1 &
    fi
else
	# Linux
    ELECTRON="$APP_PATH/voiden"
    if [ ! -f "$ELECTRON" ]; then
        # Try alternate location
        ELECTRON="$APP_PATH/Voiden"
    fi

    if [ ! -f "$ELECTRON" ]; then
		echo "Voiden executable not found at: $APP_PATH"
        exit 1
    fi

    # See the matching macOS branch above for why.
    if [ -n "$IS_CLI_SUBCOMMAND" ]; then
        CLI_JS="$APP_PATH/resources/app.asar/.vite/build/voiden-cli.js"
        exec env ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI_JS" "$@"
    fi

    # Process arguments and resolve paths
    RESOLVED_ARGS=()
    
    for arg in "$@"; do
        # Skip flags (they were already handled)
        if [[ "$arg" =~ ^- ]]; then
            continue
        fi
        
        # Resolve the path
        resolved_path=$(resolve_path "$arg")
        RESOLVED_ARGS+=("$resolved_path")
    done

    # Launch detached from terminal with proper argument passing
    if [ ${#RESOLVED_ARGS[@]} -eq 0 ]; then
        # No arguments, just open the app
        nohup "$ELECTRON" > /dev/null 2>&1 &
    else
        # Pass resolved arguments directly, detached
        nohup "$ELECTRON" "${RESOLVED_ARGS[@]}" > /dev/null 2>&1 &
    fi
fi

exit 0