#!/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.

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-worktrees/$REPO_NAME}"
STATE_ROOT="${BURST_STATE_DIR:-$HOME/.burst}/worktrees/$REPO_NAME"

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

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

  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

  rm -rf "$state_path"
}

if [[ -n "$TOTAL_OPTIONS" ]]; then
  for option in $(seq 1 "$TOTAL_OPTIONS"); do
    remove_option "$option"
  done
else
  shopt -s nullglob
  for path in "$WORKTREES_ROOT/${TASK_SLUG}-opt"*; do
    option="${path##*-opt}"
    remove_option "$option"
  done
fi

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