#!/bin/bash
# Delete worktree without merging
# Usage: ./workflow/abandon <name>

set -e

NAME="$1"
WORKTREE_BASE="worktrees"

if [[ -z "$NAME" ]]; then
    echo "Usage: ./workflow/abandon <name>"
    echo ""
    ./workflow/status
    exit 1
fi

# Find worktree
WORKTREE_PATH=$(find "$WORKTREE_BASE" -mindepth 2 -maxdepth 2 -type d -name "$NAME" 2>/dev/null | head -1)

if [[ -z "$WORKTREE_PATH" ]]; then
    echo "Error: Worktree '$NAME' not found"
    exit 1
fi

BRANCH="work/$NAME"
CODEBASE="codebase"

# Check if this is a proper git worktree or a legacy directory
IS_GIT_WORKTREE=false
if [[ -f "$WORKTREE_PATH/.git" ]]; then
    IS_GIT_WORKTREE=true
fi

# Show what will be lost (worktree .git file makes git -C work)
COMMITS=$(git -C "$WORKTREE_PATH" rev-list --count main..HEAD 2>/dev/null || echo "0")
CHANGED=$(git -C "$WORKTREE_PATH" status --porcelain 2>/dev/null | wc -l)

echo "Abandoning: $NAME"
echo "  Path: $WORKTREE_PATH"
echo "  Commits that will be lost: $COMMITS"
echo "  Uncommitted changes: $CHANGED"
echo ""

read -p "Are you sure? This cannot be undone. [y/N] " -n 1 -r
echo

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 1
fi

# Remove worktree and branch
echo "Removing..."
if [[ "$IS_GIT_WORKTREE" == "true" ]]; then
    # Proper git worktree - use git worktree remove
    git -C "$CODEBASE" worktree remove "$(pwd)/$WORKTREE_PATH" --force 2>/dev/null || rm -rf "$WORKTREE_PATH"
    git -C "$CODEBASE" branch -D "$BRANCH" 2>/dev/null || true
else
    # Legacy directory - just remove it
    echo "(Legacy directory, not a git worktree)"
    rm -rf "$WORKTREE_PATH"
fi

# Remove dated directory if empty
DATED_DIR=$(dirname "$WORKTREE_PATH")
rmdir "$DATED_DIR" 2>/dev/null || true

# Refresh symlinks
"$(dirname "$0")/refresh"

echo "Abandoned: $NAME"
