#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${SKILLHUB_CLI_BASE_URL:-https://updates.celab.top/skillhub-cli}"
INSTALL_DIR="${SKILLHUB_CLI_INSTALL_DIR:-$HOME/.local/bin}"
TARGET_NAME="${SKILLHUB_CLI_TARGET_NAME:-skillhub}"
TARGET_PATH="${INSTALL_DIR}/${TARGET_NAME}"

log() {
  printf '[skillhub-install] %s\n' "$1"
}

fail() {
  printf '[skillhub-install] %s\n' "$1" >&2
  exit 1
}

need_command() {
  command -v "$1" >/dev/null 2>&1 || fail "Missing required command: $1"
}

detect_arch() {
  local arch
  arch="$(uname -m)"
  case "$arch" in
    arm64|aarch64)
      printf 'arm64'
      ;;
    x86_64|amd64)
      printf 'x64'
      ;;
    *)
      fail "Unsupported macOS architecture: $arch"
      ;;
  esac
}

download_binary() {
  local arch="$1"
  local url="${BASE_URL}/skillhub-macos-${arch}"
  local temp_file
  temp_file="$(mktemp "${TMPDIR:-/tmp}/skillhub.XXXXXX")"
  log "Downloading ${url}"
  curl -fsSL "$url" -o "$temp_file"
  printf '%s' "$temp_file"
}

install_binary() {
  local source_file="$1"
  mkdir -p "$INSTALL_DIR"
  mv "$source_file" "$TARGET_PATH"
  chmod +x "$TARGET_PATH"
}

clear_quarantine() {
  if command -v xattr >/dev/null 2>&1; then
    xattr -d com.apple.quarantine "$TARGET_PATH" >/dev/null 2>&1 || true
  fi
}

adhoc_sign() {
  if command -v codesign >/dev/null 2>&1; then
    log "Applying local ad-hoc signature"
    codesign --force --sign - "$TARGET_PATH" >/dev/null 2>&1 || true
  fi
}

print_next_steps() {
  log "Installed to: $TARGET_PATH"
  if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    printf '\n%s\n' "Your PATH does not include ${INSTALL_DIR}."
    printf '%s\n' "Add this line to ~/.zshrc or ~/.bash_profile:"
    printf '  export PATH="%s:$PATH"\n\n' "$INSTALL_DIR"
  fi
  printf '%s\n' "Common commands:"
  printf '%s\n' "  skillhub login"
  printf '%s\n' "  skillhub register"
  printf '%s\n' "  skillhub search <keyword>"
  printf '%s\n' "  skillhub pull <slug>"
}

main() {
  need_command curl
  need_command uname
  local arch temp_file
  arch="$(detect_arch)"
  temp_file="$(download_binary "$arch")"
  install_binary "$temp_file"
  clear_quarantine
  adhoc_sign
  print_next_steps
}

main "$@"
