#!/usr/bin/env bash
# Browser-use CLI installer — bash, no desktop app.
#
#   bash install.sh                    install the published package globally
#   bash install.sh ./lorde-browser-use-0.3.6.tgz   install a local tarball
#
# Installs the `browser-use` / `browser` / `lorde` commands and verifies them.
# The web GUI ships inside the package: `browser-use gui` serves it on
# http://127.0.0.1:4200 with the CLI's own headless backend (no Electron).
set -euo pipefail

PACKAGE_NAME="lorde-browser-use"
MIN_NODE_MAJOR=20
SOURCE="${1:-$PACKAGE_NAME@latest}"

say()  { printf '%s\n' "$*"; }
fail() { printf 'error: %s\n' "$*" >&2; exit 1; }

command -v node >/dev/null 2>&1 || fail "node is not installed. Install Node.js ${MIN_NODE_MAJOR}+ first (https://nodejs.org)."
command -v npm  >/dev/null 2>&1 || fail "npm is not installed."

NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
if [ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]; then
  fail "Node.js ${NODE_MAJOR} is too old; ${MIN_NODE_MAJOR}+ is required."
fi
say "node $(node -v) · npm $(npm -v)"

# Global install. On a locked-down machine the prefix is not writable; fall back
# to a user-owned prefix and tell the user how to put it on PATH.
if ! npm install -g "$SOURCE" --no-fund --no-audit; then
  say "global prefix not writable — installing into ~/.local instead"
  npm install -g "$SOURCE" --prefix "$HOME/.local" --no-fund --no-audit
  BIN_DIR="$HOME/.local/bin"
  say ""
  say "Add this to your shell profile, then reopen the terminal:"
  say "  export PATH=\"$BIN_DIR:\$PATH\""
  export PATH="$BIN_DIR:$PATH"
fi

if ! command -v browser-use >/dev/null 2>&1; then
  say "warning: browser-use is installed but not on PATH yet."
fi

say ""
say "installed: $(browser-use --version 2>/dev/null || echo "$PACKAGE_NAME")"
say ""
say "Next:"
say "  browser-use gui --open     web GUI on http://127.0.0.1:4200 (no desktop app)"
say "  browser-use               interactive TUI"
say "  browser-use \"open example.com and read the headline\""
say "  browser-use help"
