#!/usr/bin/env bash
# Thin wrapper around the official parallel-cli.
# Auto-installs if not found; ensures non-interactive API key auth.

set -euo pipefail

INSTALL_URL="https://parallel.ai/install.sh"

install_parallel_cli() {
    echo "parallel-cli not found — installing..." >&2
    if curl -fsSL "$INSTALL_URL" | bash >&2; then
        # installer puts binary in ~/.local/bin (symlink) and ~/.local/share/parallel-cli (files)
        export PATH="$HOME/.local/bin:$PATH"
        if ! command -v parallel-cli &>/dev/null; then
            echo "Error: parallel-cli installed but not found in PATH" >&2
            echo "Add ~/.local/bin to your PATH and try again" >&2
            exit 1
        fi
        echo "parallel-cli installed successfully" >&2
    else
        echo "Error: failed to install parallel-cli" >&2
        echo "Install manually: curl -fsSL $INSTALL_URL | bash" >&2
        echo "Or: pip install parallel-web-tools (requires Python)" >&2
        exit 1
    fi
}

# Allow --version, --help, and no-arg invocation without API key
# Check key first so auth failures are immediate and clear before any network activity
case "${1:-}" in
    "" | --version | --help | -h | help) ;;
    *)
        if [[ -z "${PARALLEL_API_KEY:-}" ]]; then
            echo "Error: PARALLEL_API_KEY not set" >&2
            echo "Get your key from: https://platform.parallel.ai" >&2
            echo "Set it in your environment or configure via OpenClaw gateway" >&2
            exit 1
        fi
        ;;
esac

# Ensure parallel-cli is available (after auth check — no install on missing key)
if ! command -v parallel-cli &>/dev/null; then
    # Check ~/.local/bin explicitly (may not be in PATH for non-interactive shells)
    if [[ -x "$HOME/.local/bin/parallel-cli" ]]; then
        export PATH="$HOME/.local/bin:$PATH"
    else
        install_parallel_cli
    fi
fi

# Pass through all arguments to parallel-cli
exec parallel-cli "$@"
