#!/usr/bin/env bash
# ============================================================================
#   Simply Language --- macOS / Linux installer
#   Usage:  curl -fsSL https://beirutsites.com/simply/install.sh | bash
# ============================================================================
set -e

VERSION="3.0.0-beta"
BASE_URL="https://beirutsites.com/simply"
INSTALL_DIR="$HOME/.simply"
BIN_DIR="$HOME/.local/bin"
SIMPLY_JS_URL="$BASE_URL/version/$VERSION/simply.js"

# -- Colors -------------------------------------------------------------------
if [ -t 1 ]; then
  BLUE="\033[1;34m"; CYAN="\033[1;36m"; GREEN="\033[1;32m"; YELLOW="\033[1;33m"
  RED="\033[1;31m"; DIM="\033[2m"; RESET="\033[0m"; BOLD="\033[1m"
else
  BLUE=""; CYAN=""; GREEN=""; YELLOW=""; RED=""; DIM=""; RESET=""; BOLD=""
fi

banner() {
  echo ""
  echo -e "${BLUE}----------------------------------------${RESET}"
  echo -e "${BLUE}    ${BOLD}Simply Language${RESET}${BLUE}   v$VERSION${RESET}"
  echo -e "${BLUE}----------------------------------------${RESET}"
  echo ""
}

step()    { echo -e "${CYAN}>${RESET} $1"; }
success() { echo -e "${GREEN}+${RESET} $1"; }
warn()    { echo -e "${YELLOW}!${RESET}  $1"; }
fail()    { echo -e "${RED}x${RESET} $1" >&2; }

ACTION="${1:-install}"

# -- Prereq: Node.js ----------------------------------------------------------
check_node() {
  if ! command -v node >/dev/null 2>&1; then
    fail "Node.js is required but not installed."
    echo ""
    echo "Install Node.js first:"
    echo -e "  ${DIM}# macOS:${RESET}"
    echo "  brew install node"
    echo ""
    echo -e "  ${DIM}# Or download from:${RESET}"
    echo "  https://nodejs.org"
    echo ""
    exit 1
  fi
  local nv
  nv=$(node --version 2>/dev/null | sed 's/v//')
  success "Node.js $nv detected"
}

install_simply() {
  banner
  step "Installing Simply to $INSTALL_DIR"
  check_node

  mkdir -p "$INSTALL_DIR" "$BIN_DIR"

  step "Downloading simply.js (the interpreter)..."
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$SIMPLY_JS_URL" -o "$INSTALL_DIR/simply.js"
  elif command -v wget >/dev/null 2>&1; then
    wget -q "$SIMPLY_JS_URL" -O "$INSTALL_DIR/simply.js"
  else
    fail "Need curl or wget to download Simply."
    exit 1
  fi
  echo "$VERSION" > "$INSTALL_DIR/version.txt"
  success "Downloaded simply.js"

  # Wrapper script
  cat > "$BIN_DIR/simply" <<'EOF'
#!/usr/bin/env bash
exec node "$HOME/.simply/simply.js" "$@"
EOF
  chmod +x "$BIN_DIR/simply"
  success "Installed simply command to $BIN_DIR"

  # PATH setup (zsh, bash)
  add_to_path() {
    local rc="$1"
    if [ -f "$rc" ] && ! grep -q ".local/bin" "$rc" 2>/dev/null; then
      echo "" >> "$rc"
      echo "# Added by Simply installer" >> "$rc"
      echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$rc"
      success "Added $BIN_DIR to PATH in $rc"
    fi
  }
  add_to_path "$HOME/.zshrc"
  add_to_path "$HOME/.bashrc"
  add_to_path "$HOME/.profile"

  # VSCode extension (optional)
  if [ -d "$HOME/.vscode/extensions" ] || command -v code >/dev/null 2>&1; then
    install_vscode_ext
  else
    warn "VSCode not detected --- skipping syntax extension. Install VSCode then re-run this script."
  fi

  echo ""
  echo -e "${GREEN}----------------------------------------${RESET}"
  success "${BOLD}Simply v$VERSION installed!${RESET}"
  echo -e "${GREEN}----------------------------------------${RESET}"
  echo ""
  echo -e "  ${DIM}Try it:${RESET}"
  echo "    simply --version"
  echo "    simply path/to/file.simply"
  echo "    simply                 (interactive REPL)"
  echo ""
  echo -e "  ${DIM}Docs:${RESET}    $BASE_URL/documentation"
  echo -e "  ${DIM}Note:${RESET}    Open a ${BOLD}new terminal${RESET} window for PATH to take effect."
  echo ""
}

install_vscode_ext() {
  step "Installing VSCode syntax extension..."
  local ext_dir="$HOME/.vscode/extensions/simply-lang.simply-lang-1.0.0"
  rm -rf "$ext_dir"
  mkdir -p "$ext_dir/syntaxes"

  local tmp_zip="/tmp/simply-runtime-mac.tmp"
  if curl -fsSL "$BASE_URL/version/$VERSION/simply-runtime-mac.zip" -o "$tmp_zip" 2>/dev/null \
     && unzip -q -o "$tmp_zip" -d "/tmp/simply-runtime-extracted" 2>/dev/null; then
    cp /tmp/simply-runtime-extracted/vscode-ext/package.json              "$ext_dir/" 2>/dev/null || true
    cp /tmp/simply-runtime-extracted/vscode-ext/language-configuration.json "$ext_dir/" 2>/dev/null || true
    cp /tmp/simply-runtime-extracted/vscode-ext/syntaxes/simply.tmLanguage.json "$ext_dir/syntaxes/" 2>/dev/null || true
    rm -rf "/tmp/simply-runtime-extracted" "$tmp_zip"
  fi

  # Clear obsolete blocklist
  local obs="$HOME/.vscode/extensions/.obsolete"
  if [ -f "$obs" ] && grep -q "simply-lang" "$obs"; then
    sed -i.bak 's/"simply-lang.simply-lang-1.0.0":true,*//g; s/,}/}/g' "$obs"
    rm -f "${obs}.bak"
  fi

  success "VSCode extension installed (restart VSCode)"
}

uninstall_simply() {
  banner
  step "Removing $INSTALL_DIR"
  rm -rf "$INSTALL_DIR"
  step "Removing $BIN_DIR/simply"
  rm -f "$BIN_DIR/simply"
  step "Removing VSCode extension"
  rm -rf "$HOME/.vscode/extensions/simply-lang.simply-lang-1.0.0"
  echo ""
  success "Simply has been uninstalled."
  echo ""
}

update_simply() {
  banner
  step "Updating Simply to v$VERSION..."
  install_simply
}

case "$ACTION" in
  install)   install_simply ;;
  update)    update_simply ;;
  uninstall) uninstall_simply ;;
  *)
    echo "Usage:"
    echo "  curl -fsSL $BASE_URL/install.sh | bash"
    echo "  curl -fsSL $BASE_URL/install.sh | bash -s update"
    echo "  curl -fsSL $BASE_URL/install.sh | bash -s uninstall"
    exit 1
    ;;
esac
