#!/bin/bash

#
# Roadcrew Update Script
# 
# Updates .roadcrew/ submodule to latest version and reinstalls commands.
# User content (context/, milestones/) is preserved.
#
# Usage:
#   bash update.sh
#   npm run roadcrew:update (if configured in package.json)
#

set -e  # Exit on any error

echo "🔄 Updating Roadcrew..."
echo ""

# Step 1: Verify we're in a project with .roadcrew/ submodule
if [ ! -d ".roadcrew" ]; then
  echo "❌ Error: .roadcrew/ submodule not found"
  echo "   This script must be run from a project with Roadcrew installed."
  echo ""
  echo "   To install Roadcrew:"
  echo "     git submodule add https://github.com/tailwind-ai/roadcrew .roadcrew"
  echo "     node .roadcrew/install.cjs"
  exit 1
fi

# Step 2: Check for uncommitted changes in .roadcrew/
if [ -d ".roadcrew/.git" ] || [ -f ".roadcrew/.git" ]; then
  cd .roadcrew
  if ! git diff-index --quiet HEAD -- 2>/dev/null; then
    echo "⚠️  Warning: .roadcrew/ submodule has uncommitted changes"
    echo "   These changes will be lost during update."
    echo ""
    read -p "   Continue? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      echo "Update cancelled."
      exit 0
    fi
  fi
  cd ..
fi

# Step 3: Pull latest submodule
echo "Pulling latest .roadcrew/ submodule..."
git submodule update --remote .roadcrew

if [ $? -ne 0 ]; then
  echo ""
  echo "❌ Error: Failed to update submodule"
  echo "   Check git configuration and network connectivity."
  exit 1
fi

echo "✓ Submodule updated"
echo ""

# Step 4: Reinstall commands (with --update flag to skip template creation)
echo "Reinstalling commands..."
node .roadcrew/install.cjs --update

if [ $? -ne 0 ]; then
  echo ""
  echo "❌ Error: Failed to reinstall commands"
  echo "   Check node installation and .roadcrew/install.cjs"
  exit 1
fi

echo ""
echo "✅ Roadcrew updated successfully!"
echo ""

# Step 5: Show changelog (last 5 commits)
echo "New features available:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
git -C .roadcrew log --oneline --pretty=format:"  %Cgreen%h%Creset %s" -5
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Step 6: Check for breaking changes
CURRENT_VERSION=$(git -C .roadcrew describe --tags --abbrev=0 2>/dev/null || echo "unknown")
echo "Current version: $CURRENT_VERSION"
echo ""
echo "See full changelog: https://github.com/tailwind-ai/roadcrew/blob/main/CHANGELOG.md"
echo ""

