# Create a new worktree and branch from within current git directory.
ga() {
  if [[ -z $1 ]]; then
    echo "Usage: ga [branch name]"
    return 1
  fi

  local branch="$1"
  local base="${PWD##*/}"
  local slug="${branch//\//-}"
  local wt_path="../${base}--${slug}"

  git worktree add -b "$branch" "$wt_path" || return 1
  mise trust "$wt_path"
  cd "$wt_path" || return 1
}

# Remove worktree and branch from within active worktree directory.
gd() {
  if gum confirm "Remove worktree and branch?"; then
    local cwd branch root worktree

    cwd="$PWD"
    worktree="${cwd##*/}"

    # split on first `--`
    root="${worktree%%--*}"

    # Protect against accidentally nuking a non-worktree directory
    if [[ $root != "$worktree" ]]; then
      branch=$(git branch --show-current 2>/dev/null)
      cd "../$root" || return 1
      git worktree remove "$cwd" --force || return 1
      if [[ -n $branch ]]; then
        git branch -D "$branch"
      fi
    fi
  fi
}
