#!/bin/bash
# Create a new worktree with context files
# Usage: ./workflow/start <name> [purpose]

set -e

NAME="$1"
PURPOSE="${2:-No description provided}"
WORKTREE_BASE="worktrees"
TODAY=$(date +%Y%m%d)
NOW=$(date -Iseconds)

if [[ -z "$NAME" ]]; then
    echo "Usage: ./workflow/start <name> [purpose]"
    echo "Example: ./workflow/start feature-auth 'OAuth implementation'"
    exit 1
fi

# Ensure we're in project root
if [[ ! -d "project" ]]; then
    echo "Error: Must run from project root (project/ not found)"
    exit 1
fi

# Create dated directory if needed
mkdir -p "$WORKTREE_BASE/$TODAY"

WORKTREE_PATH="$WORKTREE_BASE/$TODAY/$NAME"
BRANCH="work/$NAME"

# Check if worktree already exists anywhere
EXISTING=$(find "$WORKTREE_BASE" -mindepth 2 -maxdepth 2 -type d -name "$NAME" 2>/dev/null | head -1)
if [[ -n "$EXISTING" ]]; then
    echo "Error: Worktree '$NAME' already exists at $EXISTING"
    exit 1
fi

echo "Creating worktree: $NAME"

# Create branch and worktree (codebase is the git repo)
CODEBASE="codebase"
git -C "$CODEBASE" branch "$BRANCH" 2>/dev/null || true
git -C "$CODEBASE" worktree add "$(pwd)/$WORKTREE_PATH" "$BRANCH"

# Create per-worktree HANDOFF.md
cat > "$WORKTREE_PATH/HANDOFF.md" << EOF
# $NAME

## Goal
$PURPOSE

## Current State
- [ ] Initial setup

## Key Files
<!-- List important files as you work -->

## Blockers
None

## Next Steps
1. Begin implementation
EOF

# Create per-worktree STATUS.md (machine-readable)
cat > "$WORKTREE_PATH/STATUS.md" << EOF
phase: started
blocked: false
blocker_reason:
purpose: $PURPOSE
started: $TODAY
last_modified: $NOW
EOF

# Install git post-commit hook for automatic heartbeat
# In a worktree, .git is a file pointing to the worktree dir in main repo
WORKTREE_GIT_DIR="$CODEBASE/.git/worktrees/$NAME"
HOOKS_DIR="$WORKTREE_GIT_DIR/hooks"
mkdir -p "$HOOKS_DIR"
cat > "$HOOKS_DIR/post-commit" << 'HOOKEOF'
#!/bin/bash
# Auto-update STATUS.md on commit (heartbeat)
if [[ -f "STATUS.md" ]]; then
    sed -i "s/^last_modified:.*/last_modified: $(date -Iseconds)/" STATUS.md
fi
HOOKEOF
chmod +x "$HOOKS_DIR/post-commit"

# Update time-based symlinks
"$(dirname "$0")/refresh"

echo ""
echo "Worktree created: $WORKTREE_PATH"
echo "Branch: $BRANCH"
echo ""
echo "Context files created:"
echo "  $WORKTREE_PATH/HANDOFF.md  - Update as you work"
echo "  $WORKTREE_PATH/STATUS.md   - Machine-readable state"
echo ""
echo "To start working:"
echo "  cd $WORKTREE_PATH"
