#!/bin/bash
# Update worktree phase
# Usage: ./workflow/phase <name> <phase>
# Phases: started, planning, implementation, testing, review, blocked, done

set -e

NAME="$1"
PHASE="$2"
WORKTREE_BASE="worktrees"
VALID_PHASES="started planning implementation testing review blocked done"

if [[ -z "$NAME" ]] || [[ -z "$PHASE" ]]; then
    echo "Usage: ./workflow/phase <name> <phase>"
    echo "Phases: $VALID_PHASES"
    exit 1
fi

# Validate phase
if [[ ! " $VALID_PHASES " =~ " $PHASE " ]]; then
    echo "Error: Invalid phase '$PHASE'"
    echo "Valid phases: $VALID_PHASES"
    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

STATUS_FILE="$WORKTREE_PATH/STATUS.md"

if [[ ! -f "$STATUS_FILE" ]]; then
    echo "Error: No STATUS.md in $WORKTREE_PATH"
    exit 1
fi

# Update phase
sed -i "s/^phase:.*/phase: $PHASE/" "$STATUS_FILE"
sed -i "s/^last_modified:.*/last_modified: $(date -Iseconds)/" "$STATUS_FILE"

# If phase is blocked, remind to use block command
if [[ "$PHASE" == "blocked" ]]; then
    echo "Phase set to blocked. Don't forget to set the reason:"
    echo "  ./workflow/block $NAME 'reason here'"
fi

# Touch the worktree to update mtime for symlink refresh
touch "$WORKTREE_PATH/STATUS.md"

echo "Phase updated: $NAME -> $PHASE"
