#!/bin/sh
# Installs hyai, the HostYourAI command line, and the coding agent it starts.
# Nothing runs as root. Read it before you pipe it: it is short.
set -eu

BASE="${HYAI_INSTALL_BASE:-https://hostyourai.com/cli}"
AGENT_PACKAGE="opencode-ai@1.18.31"

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

command -v node >/dev/null 2>&1 || fail "Node 20 or newer is needed (https://nodejs.org). It was not found."
command -v npm >/dev/null 2>&1 || fail "npm is needed and was not found."

NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
[ "$NODE_MAJOR" -ge 20 ] || fail "Node 20 or newer is needed, this is Node $(node -v)."

say "Installing hyai from $BASE ..."
npm install -g "$BASE/hyai-code-latest.tgz" >/dev/null

if command -v opencode >/dev/null 2>&1; then
  say "OpenCode is already installed, leaving it as it is."
else
  say "Installing the agent ($AGENT_PACKAGE, the version hyai was tested with) ..."
  npm install -g "$AGENT_PACKAGE" >/dev/null
fi

if command -v hyai >/dev/null 2>&1; then
  say ""
  say "Done. Next:"
  say "  hyai login     paste a router key from https://hostyourai.com/api-keys"
  say "  cd your-project && hyai"
else
  BIN="$(npm prefix -g)/bin"
  say ""
  say "Installed, but $BIN is not on your PATH, so the shell cannot find hyai."
  say "Add this line to ~/.zshrc or ~/.bashrc and open a new terminal:"
  say "  export PATH=\"$BIN:\$PATH\""
fi
