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

SCRIBE_SITE_URL='https://scribe.happenings.social'
SCRIBE_CLI_HOME="${SCRIBE_CLI_HOME:-$HOME/.local/share/scribe-cli}"
INSTALL_DIR="$SCRIBE_CLI_HOME/current"
ARCHIVE_URL="${SCRIBE_CLI_ARCHIVE_URL:-https://scribe.happenings.social/api/cli/archive}"
ADDED_TO_PROFILE=""

say() { printf "%s\n" "$*"; }
fail() { printf "Error: %s\n" "$*" >&2; exit 1; }
need_cmd() { command -v "$1" >/dev/null 2>&1 || fail "Missing required dependency: $1"; }

download_archive() {
  local url="$1"
  local target="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" -o "$target"
    return
  fi
  if command -v wget >/dev/null 2>&1; then
    wget -qO "$target" "$url"
    return
  fi
  fail "Missing downloader: curl or wget"
}

has_path_entry() {
  case ":$PATH:" in
    *":$1:"*) return 0 ;;
    *) return 1 ;;
  esac
}

profile_for_shell() {
  case "${SHELL##*/}" in
    zsh)
      printf "%s\n" "$HOME/.zprofile"
      ;;
    bash)
      if [ "$(uname -s)" = "Darwin" ]; then
        printf "%s\n" "$HOME/.bash_profile"
      else
        printf "%s\n" "$HOME/.bashrc"
      fi
      ;;
    fish)
      printf "%s\n" "$HOME/.config/fish/config.fish"
      ;;
    *)
      printf "%s\n" "$HOME/.profile"
      ;;
  esac
}

ensure_path_entry() {
  local bin_dir="$1"
  if has_path_entry "$bin_dir"; then
    return
  fi

  local profile_file
  profile_file="$(profile_for_shell)"
  mkdir -p "$(dirname "$profile_file")"

  local export_line
  case "${SHELL##*/}" in
    fish)
      export_line="fish_add_path $bin_dir"
      ;;
    *)
      export_line="export PATH=\"$bin_dir:\$PATH\""
      ;;
  esac

  if [ -f "$profile_file" ] && grep -F "$export_line" "$profile_file" >/dev/null 2>&1; then
    return
  fi

  printf "\n%s\n" "$export_line" >> "$profile_file"
  ADDED_TO_PROFILE="$profile_file"
}

choose_bin_dir() {
  if [ -n "${SCRIBE_CLI_BIN_DIR:-}" ]; then
    printf "%s\n" "$SCRIBE_CLI_BIN_DIR"
    return
  fi

  for candidate in "$HOME/.local/bin" "$HOME/bin" "/opt/homebrew/bin" "/usr/local/bin"; do
    if [ -d "$candidate" ] && [ -w "$candidate" ] && has_path_entry "$candidate"; then
      printf "%s\n" "$candidate"
      return
    fi
  done

  for candidate in "$HOME/.local/bin" "$HOME/bin" "/opt/homebrew/bin" "/usr/local/bin"; do
    if [ -d "$candidate" ] && [ -w "$candidate" ]; then
      printf "%s\n" "$candidate"
      return
    fi
  done

  printf "%s\n" "$HOME/.local/bin"
}

need_cmd node
need_cmd npm
need_cmd unzip
need_cmd mktemp

# The CLI runs through `node --import` (tsx), which needs Node.js 20+.
NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
[ "$NODE_MAJOR" -ge 20 ] 2>/dev/null || fail "Scribe CLI needs Node.js 20 or newer (found $(node --version 2>/dev/null || echo none)). Install the current LTS from https://nodejs.org and run this again."

TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

say "Installing Scribe CLI from $ARCHIVE_URL"
download_archive "$ARCHIVE_URL" "$TMP_DIR/scribe-cli.zip"
unzip -q "$TMP_DIR/scribe-cli.zip" -d "$TMP_DIR"

SOURCE_ROOT="$TMP_DIR/scribe-cli"
[ -d "$SOURCE_ROOT" ] || fail "Failed to unpack the Scribe CLI archive"
[ -f "$SOURCE_ROOT/web/package.json" ] || fail "Downloaded archive is missing web/package.json"

say "Installing CLI runtime dependencies..."
(cd "$SOURCE_ROOT/web" && npm install --omit=dev --ignore-scripts --no-fund --no-audit)

mkdir -p "$SCRIBE_CLI_HOME"
rm -rf "$INSTALL_DIR"
mv "$SOURCE_ROOT" "$INSTALL_DIR"
chmod +x "$INSTALL_DIR/scribe"
chmod +x "$INSTALL_DIR/web/bin/scribe.js"
chmod +x "$INSTALL_DIR/web/bin/scribe"

BIN_DIR="$(choose_bin_dir)"
mkdir -p "$BIN_DIR"

cat > "$BIN_DIR/scribe" <<EOF
#!/usr/bin/env bash
set -euo pipefail
export SCRIBE_CLI_INSTALL_ROOT="$INSTALL_DIR"
export SCRIBE_CLI_INSTALL_SITE_URL="$SCRIBE_SITE_URL"
export SCRIBE_CLI_HOME="$SCRIBE_CLI_HOME"
export SCRIBE_CLI_BIN_DIR="$BIN_DIR"
exec "$INSTALL_DIR/scribe" "\$@"
EOF
chmod +x "$BIN_DIR/scribe"

ensure_path_entry "$BIN_DIR"
export PATH="$BIN_DIR:$PATH"

say "Configuring Scribe CLI for $SCRIBE_SITE_URL"
"$BIN_DIR/scribe" config set-base-url "$SCRIBE_SITE_URL" >/dev/null
CONFIG_CHECK="$("$BIN_DIR/scribe" config show 2>/dev/null || true)"
printf "%s" "$CONFIG_CHECK" | grep -F "\"effectiveBaseUrl\": \"$SCRIBE_SITE_URL\"" >/dev/null 2>&1 || fail "Installed CLI self-check failed while saving base URL"

say "Installing global Scribe skill..."
if ! node "$INSTALL_DIR/web/bin/install-skill.js"; then
  say "Warning: Scribe CLI installed, but the global agent skill could not be installed."
fi

say ""
say "Scribe CLI installed."
say "  Binary: $BIN_DIR/scribe"
say "  App URL: $SCRIBE_SITE_URL"
say ""
say "Next commands:"
say "  scribe auth login"
say "  scribe endpoints"
say "  scribe update"
say ""
if [ -n "$ADDED_TO_PROFILE" ]; then
  say "Added $BIN_DIR to PATH in $ADDED_TO_PROFILE"
  say "Open a new terminal, or run: export PATH=\"$BIN_DIR:$PATH\""
fi
