#!/usr/bin/env bash
# TRIZ Agent source installer: pinned until the npm release is published.
set -euo pipefail
if [[ "${1:-}" == "--help" ]]; then
  printf '%s\n' 'Install the pinned TRIZ CLI from GitHub (Node.js 24+, npm, Git).' 'Usage: bash install.sh' 'Optional: TRIZ_INSTALL_DIR and TRIZ_NPM_PREFIX override install locations.' 'Project setup and provider login are separate; no credentials are collected.'
  exit 0
fi
if [[ $# -gt 0 ]]; then printf '%s\n' 'Unknown argument. Use --help.' >&2; exit 2; fi
for tool in node npm git; do command -v "$tool" >/dev/null || { printf 'Missing prerequisite: %s\n' "$tool" >&2; exit 1; }; done
node -e 'if (Number(process.versions.node.split(".")[0]) < 24) { console.error("TRIZ requires Node.js 24 or newer."); process.exit(1); }'
readonly revision=358abed38978499d9da85f65885b70716ae952a1
readonly repository=https://github.com/matt-cochran/triz.git
install_dir="${TRIZ_INSTALL_DIR:-${HOME}/.local/share/triz/${revision}}"
if [[ -e "$install_dir" && ! -d "$install_dir/.git" ]]; then printf 'Install destination already exists and is not a TRIZ checkout: %s\n' "$install_dir" >&2; exit 1; fi
if [[ ! -d "$install_dir/.git" ]]; then
  mkdir -p "$(dirname "$install_dir")"
  if ! GIT_TERMINAL_PROMPT=0 git clone "$repository" "$install_dir"; then
    printf '%s\n' 'Unable to clone the TRIZ repository. Check network connectivity and Git configuration; the installer does not collect credentials.' >&2
    exit 1
  fi
fi
if [[ "$(git -C "$install_dir" remote get-url origin)" != "$repository" ]]; then printf '%s\n' 'Existing checkout has an unexpected origin; choose another TRIZ_INSTALL_DIR.' >&2; exit 1; fi
if [[ -n "$(git -C "$install_dir" status --porcelain --untracked-files=no)" ]]; then printf '%s\n' 'Existing checkout has local changes; refusing to overwrite them.' >&2; exit 1; fi
if ! git -C "$install_dir" cat-file -e "${revision}^{commit}" 2>/dev/null; then git -C "$install_dir" fetch origin "$revision"; fi
git -C "$install_dir" checkout --detach "$revision"
[[ "$(git -C "$install_dir" rev-parse HEAD)" == "$revision" ]] || { printf '%s\n' 'Revision verification failed.' >&2; exit 1; }
(cd "$install_dir" && npm ci --ignore-scripts && npm run build)
if [[ -n "${TRIZ_NPM_PREFIX:-}" ]]; then
  npm install --global --ignore-scripts --prefix "$TRIZ_NPM_PREFIX" "$install_dir"
else
  npm install --global --ignore-scripts "$install_dir"
fi
node "$install_dir/dist/triz.js" catalog >/dev/null
printf '%s\n' 'TRIZ installed. Follow INSTALL.md to install the project skill and managed agent instructions.'

