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

usage() {
  cat <<'EOF'
usage: scripts/worktree-start [--dry-run] <branch-name> [start-ref]

Create an issue-specific git worktree under branches/<branch-name-with-slashes-replaced>.

Examples:
  scripts/worktree-start fix/issue-123-example
  scripts/worktree-start --dry-run review/pr-123-scope-check prgs/master
EOF
}

dry_run=0
if [[ "${1:-}" == "--dry-run" ]]; then
  dry_run=1
  shift
fi

if [[ $# -lt 1 || $# -gt 2 ]]; then
  usage >&2
  exit 2
fi

branch="$1"
start_ref="${2:-prgs/master}"

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/.." && pwd)"
worktree_name="${branch//\//-}"
worktree_path="$repo_root/branches/$worktree_name"

if [[ -e "$worktree_path" ]]; then
  cat >&2 <<EOF
Refusing to reuse existing branch worktree:
  $worktree_path

Inspect it manually. Do not overwrite or clean another issue's branch folder
unless that issue is explicitly assigned and cleanup is part of the task.
EOF
  exit 1
fi

if [[ "$dry_run" -eq 1 ]]; then
  printf 'repo: %s\n' "$repo_root"
  printf 'branch: %s\n' "$branch"
  printf 'start-ref: %s\n' "$start_ref"
  printf 'worktree: %s\n' "$worktree_path"
  printf 'commands:\n'
  printf '  git -C %q fetch prgs --prune\n' "$repo_root"
  printf '  git -C %q worktree add -b %q %q %q\n' \
    "$repo_root" "$branch" "$worktree_path" "$start_ref"
  exit 0
fi

git -C "$repo_root" fetch prgs --prune
git -C "$repo_root" worktree add -b "$branch" "$worktree_path" "$start_ref"
printf '%s\n' "$worktree_path"
