#!/usr/bin/env bash
# Update all spec-kit projects to latest templates
# Part of the update-spec-kit skill

set -euo pipefail

# Find all projects with .specify directories
projects=($(find ~/proj -name ".specify" -type d 2>/dev/null | sed 's|/.specify$||'))

if [ ${#projects[@]} -eq 0 ]; then
    echo "No spec-kit projects found"
    exit 0
fi

echo "Found ${#projects[@]} spec-kit projects:"
for proj in "${projects[@]}"; do
    echo "  - $proj"
done
echo ""

# Detect AI agent from existing setup
detect_agent() {
    local proj="$1"
    if [ -d "$proj/.claude" ]; then
        echo "claude"
    elif [ -d "$proj/.cursor" ]; then
        echo "cursor-agent"
    elif [ -d "$proj/.gemini" ]; then
        echo "gemini"
    elif [ -f "$proj/.github/copilot-instructions.md" ]; then
        echo "copilot"
    else
        echo "claude"  # default
    fi
}

# Update each project
for project in "${projects[@]}"; do
    agent=$(detect_agent "$project")
    echo "==> Updating: $project (agent: $agent)"

    cd "$project"

    # Run update
    specify init --here --force --ai "$agent"

    echo "    ✓ Updated"
    echo ""
done

echo "All projects updated!"
