#!/usr/bin/env bash
#
#   👻  GhostReach — one-line installer
#
#   This script downloads GhostReach and sets up the `ghostreach` command on your Mac.
#   It runs entirely locally, sends nothing on LinkedIn, and never signs you into anything.
#   Read it top-to-bottom before running if you like — it is intentionally short and plain.
#
set -euo pipefail

# The site this installer was served from (locked at deploy time).
BASE_URL="https://ghostreach.fly.dev"
VERSION="1.0.0"
TARBALL="ghostreach-${VERSION}.tgz"
DEST="$HOME/Applications/GhostReach"

# ── styling ──────────────────────────────────────────────────────────────────
if [ -t 1 ]; then
  V=$'\033[38;5;99m'; C=$'\033[38;5;51m'; G=$'\033[38;5;42m'; Y=$'\033[38;5;220m'
  R=$'\033[38;5;203m'; D=$'\033[2m'; B=$'\033[1m'; X=$'\033[0m'
else
  V=""; C=""; G=""; Y=""; R=""; D=""; B=""; X=""
fi
ok(){   printf "  ${G}✓${X} %s\n" "$1"; }
warn(){ printf "  ${Y}!${X} %s\n" "$1"; }
err(){  printf "  ${R}✗${X} %s\n" "$1"; }
step(){ printf "  ${C}•${X} %s\n" "$1"; }

printf "\n"
printf "  ${V}${B}👻  GhostReach${X}\n"
printf "  ${V}────────────────────────────────${X}\n"
printf "  ${D}Safe, rate-limited LinkedIn outreach on autopilot.${X}\n\n"

# ── sanity: macOS + tools ─────────────────────────────────────────────────────
if [ "$(uname)" != "Darwin" ]; then
  err "GhostReach is a Mac app. This installer only runs on macOS."
  exit 1
fi
for tool in curl tar; do
  command -v "$tool" >/dev/null 2>&1 || { err "'$tool' is required but not found."; exit 1; }
done

# ── 1. download ───────────────────────────────────────────────────────────────
step "Downloading GhostReach ${VERSION}…"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
if ! curl -fSL --progress-bar "${BASE_URL}/${TARBALL}" -o "${TMP}/${TARBALL}"; then
  err "Couldn't download GhostReach from ${BASE_URL}. Check your connection and try again."
  exit 1
fi
ok "Downloaded"

# ── 2. unpack into ~/Applications/GhostReach ─────────────────────────────────
step "Unpacking…"
tar -xzf "${TMP}/${TARBALL}" -C "$TMP"            # → $TMP/ghostreach/
if [ ! -d "${TMP}/ghostreach" ]; then
  err "The download looks incomplete. Please re-run the installer."
  exit 1
fi
mkdir -p "$(dirname "$DEST")"
rm -rf "$DEST"
mv "${TMP}/ghostreach" "$DEST"
ok "Installed to ${DEST/#$HOME/~}"

# ── 3. hand off to the bundled setup (Node check, PATH, guide) ───────────────
if [ -x "$DEST/install.sh" ] || [ -f "$DEST/install.sh" ]; then
  printf "\n"
  bash "$DEST/install.sh"
else
  # Fallback: minimal PATH wiring if the bundled installer is missing.
  chmod +x "$DEST/bin/ghostreach" 2>/dev/null || true
  for CAND in /usr/local/bin /opt/homebrew/bin; do
    if [ -d "$CAND" ] && [ -w "$CAND" ]; then
      ln -sf "$DEST/bin/ghostreach" "$CAND/ghostreach"
      ok "Installed command: ${B}ghostreach${X}"; break
    fi
  done
  printf "\n  ${G}${B}All set!${X} Run ${V}ghostreach welcome${X} to get started.\n\n"
fi
