#!/usr/bin/env zsh
# safe_checkout.sh — safely switch branches, auto-stashing dirty state
# Usage: zsh scripts/conductor/safe_checkout.sh <branch>
# RULE-610: NEVER raw `git checkout` — always use this script.

set -euo pipefail

branch="${1:-main}"
REPO="$(git rev-parse --show-toplevel 2>/dev/null || echo "$HOME/dev/orxaq")"
cd "$REPO"

current="$(git branch --show-current 2>/dev/null || echo "DETACHED")"

if [[ "$current" == "$branch" ]]; then
  echo "[safe_checkout] Already on $branch"
  exit 0
fi

# Stash if dirty
if ! git diff --quiet HEAD 2>/dev/null || ! git diff --cached --quiet 2>/dev/null; then
  stash_msg="safe_checkout: auto-stash before switching to $branch (from $current)"
  git stash push -u -m "$stash_msg" 2>/dev/null || true
  echo "[safe_checkout] Stashed dirty state"
fi

git checkout "$branch"
echo "[safe_checkout] Now on $branch"
