#!/usr/bin/env bash
# FFCTK Installer — Linux / macOS
# Usage: curl -fsSL ${FFCTK_INSTALL_BASE}/install.sh | bash
set -euo pipefail

FFCTK_INSTALL_BASE="${FFCTK_INSTALL_BASE:-https://ffai.faradayfuture.com}"
INSTALL_DIR="${HOME}/.local/bin"
BIN_NAME="ffctk"

detect_platform() {
  local os arch
  os=$(uname -s)
  arch=$(uname -m)
  case "$os" in
    Darwin) os="macos";;
    Linux) os="linux";;
    *) echo "Unsupported OS: $os" >&2; exit 1;;
  esac
  case "$arch" in
    x86_64|amd64) arch="x64";;
    arm64|aarch64) arch="arm64";;
    *) echo "Unsupported arch: $arch" >&2; exit 1;;
  esac
  if [ "$os" = "linux" ] && [ "$arch" = "arm64" ]; then
    echo "Linux arm64 binary not yet packaged" >&2; exit 1
  fi
  echo "${os}-${arch}"
}

main() {
  local platform url tmp
  platform=$(detect_platform)
  url="${FFCTK_INSTALL_BASE}/ffctk/ffctk-${platform}"
  echo "Downloading ${BIN_NAME} (${platform}) from ${url}"
  mkdir -p "${INSTALL_DIR}"
  tmp=$(mktemp)
  if ! curl -fSL --progress-bar -o "${tmp}" "${url}"; then
    echo "Download failed. Check FFCTK_INSTALL_BASE and your network." >&2
    rm -f "${tmp}"
    exit 1
  fi
  chmod +x "${tmp}"
  mv "${tmp}" "${INSTALL_DIR}/${BIN_NAME}"
  # macOS: strip quarantine attr so Gatekeeper doesn't block
  if [ "$(uname -s)" = "Darwin" ]; then
    xattr -d com.apple.quarantine "${INSTALL_DIR}/${BIN_NAME}" 2>/dev/null || true
  fi
  echo "✅ Installed to ${INSTALL_DIR}/${BIN_NAME}"
  if [[ ":$PATH:" != *":${INSTALL_DIR}:"* ]]; then
    echo ""
    echo "⚠️  ${INSTALL_DIR} is not on your PATH. Add this to your shell rc:"
    echo "    export PATH=\"\$HOME/.local/bin:\$PATH\""
  fi
  echo ""
  echo "Next steps:"
  echo "  1. Generate a token at ${FFCTK_INSTALL_BASE}/ai-usage/me/tokens"
  echo "  2. ffctk login <your-token>"
  echo "  3. ffctk start"
}

main "$@"
