#!/bin/sh
# Pixio setup — macOS and Linux
#
#   curl -fsSL https://beta.pixio.myapps.ai/downloads/pixio-setup.sh | bash
#
# One wizard for both plugins. It picks the host app, installs and signs in the
# agent CLI you choose, installs the plugin, and then VERIFIES both rather than
# assuming — a setup script that reports success it did not check is worse than
# no script at all.
#
# Piped to a shell, stdin is the script itself, so every prompt reads from
# /dev/tty. Without that, `read` silently consumes the rest of the script.
#
# The CLI install and sign-in commands mirror
# apps/blender-plugin/addon/cli.py (`install_command` / `signin_command`);
# change them in both places.

set -eu

BASE='https://beta.pixio.myapps.ai/downloads'
BOLD=$(printf '\033[1m'); DIM=$(printf '\033[2m'); RED=$(printf '\033[31m')
GREEN=$(printf '\033[32m'); YELLOW=$(printf '\033[33m'); CYAN=$(printf '\033[36m')
MAGENTA=$(printf '\033[35m'); OFF=$(printf '\033[0m')

step() { printf '\n  %s%s%s\n' "$CYAN" "$1" "$OFF"; }
ok()   { printf '    %sOK%s  %s\n' "$GREEN" "$OFF" "$1"; }
warn() { printf '    %s!%s   %s\n' "$YELLOW" "$OFF" "$1"; }
die()  { printf '\n    %sX%s   %s\n\n' "$RED" "$OFF" "$1" >&2; exit 1; }
ask()  { printf '    %s ' "$1"; read -r REPLY < /dev/tty || REPLY=''; }

if [ ! -t 0 ] && [ ! -e /dev/tty ]; then
  die "This setup asks questions and needs a terminal. Download it and run it directly instead."
fi

printf '\n  %sPixio — plugin setup%s\n' "$MAGENTA$BOLD" "$OFF"
printf '  %sYour own agent, running in your own app. Nothing is proxied through Pixio.%s\n' "$DIM" "$OFF"

case "$(uname -s)" in
  Darwin) PLATFORM=mac ;;
  *)      PLATFORM=linux ;;
esac

# ── which host app ─────────────────────────────────────────────────────────
if [ "$PLATFORM" = mac ]; then
  BLENDER_ROOT="$HOME/Library/Application Support/Blender"
  [ -d "/Applications" ] && AE_FOUND=$(ls -d /Applications/Adobe\ After\ Effects*/ 2>/dev/null | head -1) || AE_FOUND=''
else
  BLENDER_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}/blender"
  AE_FOUND=''  # After Effects does not exist on Linux
fi
[ -d "$BLENDER_ROOT" ] && BLENDER_FOUND=yes || BLENDER_FOUND=''

step 'Which app?'
if [ "$PLATFORM" = linux ]; then
  APP=blender
  ok 'Blender (After Effects is not available on Linux)'
else
  printf '    [1] After Effects%s\n' "$([ -n "$AE_FOUND" ] && echo ' (found)' || echo '')"
  printf '    [2] Blender%s\n' "$([ -n "$BLENDER_FOUND" ] && echo ' (found)' || echo '')"
  ask 'Choose [1]:'
  case "$REPLY" in 2) APP=blender ;; *) APP=ae ;; esac
fi
[ "$APP" = ae ] && APP_NAME='After Effects' || APP_NAME='Blender'
ok "Setting up for $APP_NAME"

# ── the agent CLI ──────────────────────────────────────────────────────────
# PATH first, then where each CLI actually installs itself: a GUI app does not
# inherit a login shell's PATH, and neither does this script when the user has
# a version manager.
find_cli() {
  engine="$1"
  case "$engine" in
    claude) names='claude' ;;
    codex)  names='codex' ;;
    cursor) names='cursor-agent agent' ;;
  esac
  for name in $names; do
    found=$(command -v "$name" 2>/dev/null || true)
    [ -n "$found" ] && { printf '%s' "$found"; return 0; }
  done
  for name in $names; do
    for dir in "$HOME/.local/bin" /opt/homebrew/bin /usr/local/bin "$HOME/.claude/local" "$HOME/.cursor/bin"; do
      [ -x "$dir/$name" ] && { printf '%s' "$dir/$name"; return 0; }
    done
    for dir in "$HOME"/.nvm/versions/node/*/bin "$HOME"/.volta/bin "$HOME"/.asdf/shims; do
      [ -x "$dir/$name" ] && { printf '%s' "$dir/$name"; return 0; }
    done
  done
  return 1
}

engine_install() {
  case "$1" in
    claude) echo 'curl -fsSL https://claude.ai/install.sh | bash' ;;
    codex)  echo 'npm i -g @openai/codex' ;;
    cursor) echo 'curl https://cursor.com/install -fsS | bash' ;;
  esac
}
engine_login_arg() { case "$1" in claude) echo '/login' ;; *) echo 'login' ;; esac; }
engine_name() {
  case "$1" in claude) echo 'Claude Code' ;; codex) echo 'Codex' ;; cursor) echo 'Cursor' ;; esac
}

step 'Which agent?'
index=1
for id in claude codex cursor; do
  mark=''
  find_cli "$id" >/dev/null 2>&1 && mark=' (installed)'
  printf '    [%s] %s%s\n' "$index" "$(engine_name "$id")" "$mark"
  index=$((index + 1))
done
ask 'Choose [1]:'
case "$REPLY" in 2) ENGINE=codex ;; 3) ENGINE=cursor ;; *) ENGINE=claude ;; esac
ENGINE_NAME=$(engine_name "$ENGINE")

if BINARY=$(find_cli "$ENGINE"); then
  ok "$ENGINE_NAME already installed"
else
  step "Installing $ENGINE_NAME"
  printf '    %s%s%s\n' "$DIM" "$(engine_install "$ENGINE")" "$OFF"
  sh -c "$(engine_install "$ENGINE")" </dev/tty || die "That failed. Run it yourself in a terminal, then re-run this setup."
  PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"
  export PATH
  BINARY=$(find_cli "$ENGINE") || die "$ENGINE_NAME still not found. Open a NEW terminal and re-run this setup."
  ok "$ENGINE_NAME installed"
fi

step "Signing in to $ENGINE_NAME"
printf '    %sA browser window opens. Finish there, then come back.%s\n' "$DIM" "$OFF"
if "$BINARY" "$(engine_login_arg "$ENGINE")" </dev/tty; then
  ok 'Signed in'
else
  warn "Could not sign in automatically. Run this when setup finishes:"
  printf '        "%s" %s\n' "$BINARY" "$(engine_login_arg "$ENGINE")"
fi

# ── the plugin ─────────────────────────────────────────────────────────────
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

if [ "$APP" = ae ]; then
  pgrep -x 'After Effects' >/dev/null 2>&1 && die 'After Effects is open. Close it and re-run this setup.'
  step 'Installing the After Effects extension'
  TARGET="$HOME/Library/Application Support/Adobe/CEP/extensions/com.pixio.after-effects-plugin"
  curl -fsSL "$BASE/after-effects/Pixio-After-Effects-latest.zip" -o "$TMP/ae.zip" || die 'Download failed.'
  rm -rf "$TARGET"
  mkdir -p "$TARGET"
  unzip -oq "$TMP/ae.zip" -d "$TARGET" || die 'Could not unpack the extension.'
  [ -f "$TARGET/CSXS/manifest.xml" ] || die "The extension did not unpack correctly into $TARGET."
  ok "Installed to $TARGET"
else
  pgrep -x blender >/dev/null 2>&1 && die 'Blender is open. Close it and re-run this setup.'
  step 'Installing the Blender add-on'
  [ -d "$BLENDER_ROOT" ] || die "No Blender configuration folder found. Start Blender once so it creates one, then re-run this setup."
  curl -fsSL "$BASE/blender/Pixio-Blender-latest.zip" -o "$TMP/blender.zip" || die 'Download failed.'
  INSTALLED=0
  for VERSION in "$BLENDER_ROOT"/*/; do
    [ -d "$VERSION" ] || continue
    ADDONS="$VERSION/scripts/addons"
    mkdir -p "$ADDONS"
    rm -rf "$ADDONS/pixio_blender"
    unzip -oq "$TMP/blender.zip" -d "$ADDONS" || continue
    if [ -f "$ADDONS/pixio_blender/__init__.py" ]; then
      ok "Blender $(basename "$VERSION")"
      INSTALLED=$((INSTALLED + 1))
    fi
  done
  [ "$INSTALLED" -gt 0 ] || die 'Could not install into any Blender version.'
fi

# ── done ───────────────────────────────────────────────────────────────────
printf '\n  %sDone.%s\n' "$GREEN$BOLD" "$OFF"
if [ "$APP" = ae ]; then
  echo '  1. Open After Effects, then Window > Extensions > Pixio'
  echo '  2. After Effects > Settings > Scripting & Expressions, tick "Allow Scripts to Write Files and Access Network"'
  echo "  3. On the Chat tab pick $ENGINE_NAME and describe what to build"
else
  echo '  1. Open Blender, then Edit > Preferences > Add-ons, search "Pixio", tick it'
  echo '  2. In the 3D viewport press N and choose the Pixio tab'
  echo "  3. Pick $ENGINE_NAME at the top of the Chat tab and describe the scene"
fi
echo ''
