#!/usr/bin/env bash
# ============================================================================
#  Vespryx desktop tools, one-click setup for macOS and Linux.
#
#  This file is plain text on purpose. Read it before you run it. It:
#    1. checks for Node, and installs it with Homebrew on macOS if missing
#    2. downloads https://vespryx.com/download/vespryx-tools.zip
#    3. unpacks it to ~/Vespryx
#    4. sets up the TradingView bridge and installs your token
#    5. runs pre-flight, which names anything still wrong
#    6. sets Vespryx to start at login, and starts it now
#
#  It installs nothing else. The one thing it leaves behind is a login entry
#  (a LaunchAgent on macOS, an autostart entry on Linux) so Vespryx starts
#  with your computer, and "node tools/autostart.mjs --uninstall" from the
#  Vespryx folder removes it.
#
#  YOU DO NOT NEED ANY OF THIS to see Vespryx levels in the TradingView
#  desktop app. Drawings live on your TradingView account, so a symbol painted
#  in Chrome is already painted in the desktop app and on your phone. This kit
#  is for driving the desktop app directly, and for letting a coding agent read
#  and draw on your chart.
#
#  Run it with:   bash ~/Downloads/vespryx-setup.sh
# ============================================================================
set -uo pipefail

DEST="$HOME/Vespryx"
# A temp DIRECTORY, then a named file inside it. `$(mktemp ...).zip` reads as one
# path and is two: mktemp creates a file and the .zip is appended after the fact,
# so the download goes somewhere mktemp never made and the file it did make is
# left behind empty on every run.
TMPDIR_VX="$(mktemp -d -t vespryx-XXXXXX)"
ZIP="$TMPDIR_VX/vespryx-tools.zip"
KITURL="https://vespryx.com/download/vespryx-tools.zip"
trap 'rm -rf "$TMPDIR_VX"' EXIT

say() { printf '  %s\n' "$*"; }
die() { printf '\n  %s\n\n' "$*"; exit 1; }

printf '\n  Vespryx desktop tools\n  ---------------------\n  Installing to: %s\n\n' "$DEST"

# --- 1. Node ----------------------------------------------------------------
if command -v node >/dev/null 2>&1; then
  say "[1/6] Node is already installed ($(node --version))."
else
  say "[1/6] Node is not installed."
  if [ "$(uname -s)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
    say "      Installing it with Homebrew, this takes a minute..."
    brew install node || die "Homebrew could not install Node. Install it from https://nodejs.org and run this again."
  else
    # Deliberately NOT piping a vendor install script into a shell here. This
    # file already asks for a lot of trust; adding a second remote script that
    # it runs unread would be asking for more than it needs.
    die "Install Node 20 or newer from https://nodejs.org (or your package manager) and run this again."
  fi
fi

NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
if [ "$NODE_MAJOR" -lt 20 ]; then
  die "Node $NODE_MAJOR is too old. Version 20 or newer is needed: https://nodejs.org"
fi

# --- 2. download ------------------------------------------------------------
say "[2/6] Downloading the toolkit..."
curl -fsSL -o "$ZIP" "$KITURL" || die "The download failed. Check your internet connection and try again."

# --- 3. unpack --------------------------------------------------------------
#  unzip is not on every minimal Linux image, and GNU tar cannot read a zip at
#  all, so Python's zipfile is the fallback rather than a second dependency.
say "[3/6] Unpacking to $DEST"
mkdir -p "$DEST"
if command -v unzip >/dev/null 2>&1; then
  unzip -oq "$ZIP" -d "$DEST" || die "Could not unpack the download."
elif command -v python3 >/dev/null 2>&1; then
  python3 -m zipfile -e "$ZIP" "$DEST" || die "Could not unpack the download."
else
  die "Need either unzip or python3 to unpack the toolkit."
fi

cd "$DEST" || die "Could not enter $DEST"

# --- 4. bridge + token ------------------------------------------------------
printf '\n'
say "[4/6] Setting up the TradingView bridge."
say "      TradingView will close and reopen, which is meant to happen."
printf '\n'
node tools/setup-bridge.mjs

printf '\n  ---------------------------------------------------------------\n'
say "Now your token, so the tools can read your Vespryx data."
printf '\n'
say "  1. Open  https://vespryx.com/portal/"
say "  2. Scroll down to \"Desktop tools\""
say "  3. Press \"Show my token\", then press \"Copy\""
printf '\n'
say "Then come back here and press Enter."
printf '  ---------------------------------------------------------------\n\n'
read -r _

if [ "$(uname -s)" = "Darwin" ] && command -v pbpaste >/dev/null 2>&1; then
  pbpaste | node tools/td-token.mjs
elif command -v xclip >/dev/null 2>&1; then
  xclip -o -selection clipboard | node tools/td-token.mjs
elif command -v wl-paste >/dev/null 2>&1; then
  wl-paste | node tools/td-token.mjs
else
  # No clipboard tool. td-token.mjs reads stdin, so the terminal itself is the
  # paste target: the same install path, not a degraded one.
  printf '\n  Paste the token here, then press Enter and Ctrl-D:\n\n'
  node tools/td-token.mjs
fi

# --- 5. verify --------------------------------------------------------------
printf '\n'
say "[5/6] Checking everything..."
printf '\n'
node tools/preflight.mjs

# --- 6. start at login --------------------------------------------------------
# Nobody is going to run node tools/watch.mjs by hand. It runs in the
# background from here on, starts at login, and every launch of TradingView
# gets the debug port.
printf '\n'
say "[6/6] Setting Vespryx to start at login, and starting it now..."
printf '\n'
node tools/autostart.mjs --install

printf '\n  ---------------------------------------------------------------\n'
say "Finished. Vespryx is running in the background and starts at login."
printf '\n'
say "Open TradingView Desktop as normal. The FIRST time you open it, it will"
say "close and reopen once by itself: that is Vespryx connecting. After that"
say "your levels paint on every symbol you look at."
printf '\n'
say "Your toolkit is in:  $DEST"
printf '\n'
say "If the bridge stops working later, run this file again."
say "To take Vespryx out of your login items:  node tools/autostart.mjs --uninstall"
printf '  ---------------------------------------------------------------\n\n'
