#!/bin/sh
# Factorial Compute: install the `factorial` command, sign in, and set up
# your coding agents.
#
#   curl -LsSf https://api.factorialcompute.com/install.sh | sh -s -- inv_...
#
# It says what it will do and asks before doing any of it. Options, after the
# invitation:
#   --project   set the agents up for the current folder only, not every project
#   --yes       do not ask
#
# The command is installed with uv as its own isolated tool, so it works in
# every folder and touches no project's Python. uv is installed first if this
# machine does not have it. Everything it writes:
# https://docs.factorialcompute.com/agents/
set -eu

INVITE=""
PROJECT=""
YES=""
for arg in "$@"; do
  case "$arg" in
    --project) PROJECT=1 ;;
    --yes|-y) YES=1 ;;
    *) INVITE="$arg" ;;
  esac
done
say() { printf '%s\n' "$*"; }

if [ -n "$PROJECT" ]; then
  WHERE="this folder only ($(pwd))"
else
  WHERE="your user, so they work in every folder"
fi
say "This will:"
command -v uv >/dev/null 2>&1 || say "  - install uv, a Python tool installer, from astral.sh"
say "  - install the factorial command: uv tool install factorial-compute"
if [ -n "$INVITE" ]; then
  say "  - redeem your invitation and save the key in ~/.config/factorial/credentials, readable only by you"
fi
say "  - set up Claude Code, Codex and Cursor - those installed here - for $WHERE:"
say "      a skill (SKILL.md) saying what Factorial can do, and the factorial MCP server"
say "      as their tools, each with an API key of its own. You will see each file first."
say "Nothing else is changed. Details: https://docs.factorialcompute.com/agents/"

# Piped into sh, standard input is this script: the answer is read from the
# terminal itself. With no terminal (CI), the command line was the consent.
if [ -z "$YES" ] && (: </dev/tty) 2>/dev/null; then
  printf 'Continue? [Y/n] '
  read -r answer </dev/tty || answer=""
  case "$answer" in
    ""|y|Y|yes|Yes|YES) ;;
    *) say "Nothing was changed."; exit 0 ;;
  esac
fi

if ! command -v uv >/dev/null 2>&1; then
  say "Installing uv (a Python tool installer) first..."
  curl -LsSf https://astral.sh/uv/install.sh | sh
  PATH="$HOME/.local/bin:$PATH"
  export PATH
fi

say "Installing the factorial command..."
uv tool install --upgrade --quiet factorial-compute
uv tool update-shell >/dev/null 2>&1 || true
PATH="$(uv tool dir --bin 2>/dev/null || printf '%s' "$HOME/.local/bin"):$PATH"
export PATH

if [ -n "$PROJECT" ]; then
  if [ -n "$INVITE" ]; then
    factorial login "$INVITE" --no-agents
  fi
  factorial install --project
elif [ -n "$INVITE" ]; then
  factorial login "$INVITE" --yes
else
  factorial install --detect
fi

say ""
if [ -n "$PROJECT" ]; then
  say "Done. Open Claude Code or Cursor in $(pwd) and describe what you want to build."
else
  say "Done. Open Claude Code, Codex or Cursor in any folder and describe what you want to build."
fi
say "Open a new terminal to use the factorial command yourself."
