#!/usr/bin/env bash
# clean-worktrees.sh — Remove losing Burst worktrees for a task.
#
# Usage:
#   clean-worktrees.sh <repo-root> <task-slug> <winner-option> [<total-options>]
#
# Keeps <task-slug>-opt<winner-option>. Removes sibling option worktrees for
# the same task. Use after the winner has been picked/pushed.
#
# Worktrees live under ~/burst-prototypes/git/<repo>/ by default. Also scans
# legacy locations so pre-migration worktrees are cleaned:
#   - ~/burst-prototypes/<repo>/   (brief flat layout)
#   - ~/burst-worktrees/<repo>/    (original layout)

set -euo pipefail

if [[ $# -lt 3 ]]; then
  echo "usage: $0 <repo-root> <task-slug> <winner-option> [<total-options>]" >&2
  exit 2
fi

REPO_ROOT="$1"
TASK_SLUG="$2"
WINNER_OPTION="$3"
TOTAL_OPTIONS="${4:-}"

if [[ ! -d "$REPO_ROOT/.git" ]]; then
  echo "[clean-worktrees] ERROR: $REPO_ROOT is not a git repo root" >&2
  exit 1
fi

REPO_NAME="$(basename "$REPO_ROOT")"
WORKTREES_ROOT="${BURST_WORKTREES_ROOT:-$HOME/burst-prototypes/git/$REPO_NAME}"
FLAT_LEGACY_ROOT="$HOME/burst-prototypes/$REPO_NAME"
WORKTREES_LEGACY_ROOT="$HOME/burst-worktrees/$REPO_NAME"
STATE_ROOT="${BURST_STATE_DIR:-$HOME/.burst}/worktrees/$REPO_NAME"

# Candidate roots to clean, de-duplicated.
CANDIDATE_ROOTS=("$WORKTREES_ROOT")
for root in "$FLAT_LEGACY_ROOT" "$WORKTREES_LEGACY_ROOT"; do
  if [[ "$root" != "$WORKTREES_ROOT" ]]; then
    CANDIDATE_ROOTS+=("$root")
  fi
done

remove_at_path() {
  local worktree_path="$1"

  if [[ -d "$worktree_path" ]]; then
    echo "[clean-worktrees] removing loser worktree: $worktree_path" >&2
    git -C "$REPO_ROOT" worktree remove "$worktree_path" 2>/dev/null || rm -rf "$worktree_path"
  fi
}

remove_option() {
  local option="$1"
  local worktree_name="${TASK_SLUG}-opt${option}"
  local state_path="${STATE_ROOT}/${worktree_name}"
  local root

  if [[ "$option" == "$WINNER_OPTION" ]]; then
    return
  fi

  for root in "${CANDIDATE_ROOTS[@]}"; do
    remove_at_path "${root}/${worktree_name}"
  done

  rm -rf "$state_path"
}

collect_options_from_root() {
  local root="$1"
  local path
  local option
  local nullglob_was_on=0

  if [[ ! -d "$root" ]]; then
    return
  fi

  shopt -q nullglob && nullglob_was_on=1
  shopt -s nullglob
  for path in "$root/${TASK_SLUG}-opt"*; do
    option="${path##*-opt}"
    echo "$option"
  done
  if [[ "$nullglob_was_on" -eq 0 ]]; then
    shopt -u nullglob
  fi
}

if [[ -n "$TOTAL_OPTIONS" ]]; then
  for option in $(seq 1 "$TOTAL_OPTIONS"); do
    remove_option "$option"
  done
else
  OPTIONS=$(
    {
      for root in "${CANDIDATE_ROOTS[@]}"; do
        collect_options_from_root "$root"
      done
    } | sort -u
  )
  for option in $OPTIONS; do
    remove_option "$option"
  done
fi

echo "[clean-worktrees] kept winner: ${TASK_SLUG}-opt${WINNER_OPTION}" >&2
