#!/bin/bash
# Cleanup a specific worktree (without merging)
# Usage: cleanup-worktree.sh <product-slug> <task-id>

set -e

SLUG=$1
TASK_ID=$2

if [ -z "$SLUG" ] || [ -z "$TASK_ID" ]; then
  echo "Usage: cleanup-worktree.sh <product-slug> <task-id>" >&2
  exit 1
fi

PRODUCT_DIR="/home/aria/products/$SLUG"
MAIN_DIR="$PRODUCT_DIR/apps/main"
WORKTREE_DIR="$PRODUCT_DIR/worktrees/$TASK_ID"
STATE_FILE="$PRODUCT_DIR/.worktree-state.json"
BRANCH="task/$TASK_ID"

cd "$MAIN_DIR"

# Remove worktree
git worktree remove "$WORKTREE_DIR" --force 2>/dev/null || rm -rf "$WORKTREE_DIR"

# Remove branch
git branch -D "$BRANCH" 2>/dev/null || true
git push origin --delete "$BRANCH" 2>/dev/null || true

# Remove from state
if [ -f "$STATE_FILE" ]; then
  jq --arg id "$TASK_ID" 'del(.active[$id])' "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"
fi

echo "Cleaned up worktree: $TASK_ID"
