#!/bin/bash
# Interactive git branch switcher using fzf
# Lists all local and remote branches with a commit preview; Enter to checkout, Esc to cancel.
# Local-only branches (not pushed) are included; duplicates (same name local+remote) appear once.
#
# Requirements: git, fzf
# Install fzf:  brew install fzf  |  apt install fzf
#
# Usage:
#   bash branch-switch.sh            # run from any git repo
#   chmod +x branch-switch.sh        # make executable
#   cp branch-switch.sh ~/bin/git-sw # install globally

set -euo pipefail

if ! command -v fzf &>/dev/null; then
  echo "error: fzf is not installed. See https://github.com/junegunn/fzf" >&2
  exit 1
fi

if ! git rev-parse --git-dir &>/dev/null; then
  echo "error: not inside a git repository" >&2
  exit 1
fi

git fetch --quiet 2>/dev/null || true

branch=$(
  git branch -a \
    | grep -v '\->' \
    | sed 's/^[* ]*//; s|remotes/origin/||' \
    | sort -u \
    | fzf \
        --height=40% \
        --reverse \
        --border \
        --ansi \
        --prompt='Switch to branch: ' \
        --header='All branches  [Enter=checkout  Esc=cancel  Ctrl-C=abort]' \
        --preview='git log --oneline --color=always -20 "origin/{}" 2>/dev/null || git log --oneline --color=always -20 "{}" 2>/dev/null || echo "(no commits)"' \
        --preview-window=right:60%
)

if [ -z "$branch" ]; then
  echo "Aborted." >&2
  exit 0
fi

git checkout "$branch"
