#!/bin/sh
# HighFi installer (P-03 criterion 1): one command, Node 20+, no account.
#   curl -fsSL https://www.highfi.dev/install.sh | sh
# Clones HighFi into ~/highfi (HIGHFI_DIR to change it), installs the app, adds a `highfi` command
# to ~/.local/bin, and starts the app at http://localhost:5173 (HIGHFI_NO_START=1 to skip).
# Early access: the repository is private, so the clone needs access (ask Devin or Lenilson).
set -eu

DIR="${HIGHFI_DIR:-$HOME/highfi}"
REPO="${HIGHFI_REPO:-git@github.com:lenilsonjr/highfi.git}"
BRANCH="${HIGHFI_BRANCH:-main}"
say() { printf '%s\n' "highfi · $*"; }
fail() { printf '%s\n' "highfi · stopped: $*" >&2; exit 1; }

command -v git >/dev/null 2>&1 || fail "git is not installed (https://git-scm.com/downloads)"
command -v node >/dev/null 2>&1 || fail "Node 20 or newer is not installed (https://nodejs.org)"
command -v npm >/dev/null 2>&1 || fail "npm is not installed (it comes with Node)"
NODE_MAJOR=$(node -p 'process.versions.node.split(".")[0]')
[ "$NODE_MAJOR" -ge 20 ] || fail "Node $NODE_MAJOR found; HighFi needs Node 20 or newer (https://nodejs.org)"

if [ -d "$DIR/.git" ]; then
  say "updating $DIR"
  git -C "$DIR" pull --ff-only --quiet || fail "could not update $DIR (local changes?); run git -C $DIR status"
else
  [ -e "$DIR" ] && fail "$DIR exists and is not a HighFi checkout; set HIGHFI_DIR to another folder"
  say "cloning into $DIR"
  git clone --quiet --depth 1 --branch "$BRANCH" "$REPO" "$DIR" || fail "could not clone $REPO. HighFi is in early access: ask Devin or Lenilson for access to the repository, then run this again"
fi

APP="$DIR/frontend-prototype-v1"
say "installing the app (about a minute the first time)"
(cd "$APP" && npm ci --no-audit --no-fund --loglevel=error) || fail "npm ci failed in $APP"

BIN="$HOME/.local/bin"
mkdir -p "$BIN"
cat > "$BIN/highfi" <<LAUNCH
#!/bin/sh
# HighFi launcher, written by install.sh. Opens the app at http://localhost:5173
cd "$APP" && exec npm run dev "\$@"
LAUNCH
chmod +x "$BIN/highfi"
case ":$PATH:" in
  *":$BIN:"*) AGAIN="highfi" ;;
  *) AGAIN="$BIN/highfi   (or add $BIN to your PATH)" ;;
esac

say "installed. Next time, start it with: $AGAIN"
say "it opens on HighFi's own design file; choose New project in the project menu to onboard your codebase"
say "guide: https://www.highfi.dev/start"
if [ "${HIGHFI_NO_START:-}" = "1" ]; then exit 0; fi
say "starting: open http://localhost:5173 (Ctrl-C to stop)"
cd "$APP" && exec npm run dev
