#!/bin/bash

# Deployment script for chat-ui
# This script bumps the version in your PR branch before mergin

set -e  # Exit on any error

echo "🚀 Starting version bump..."
echo ""

# Get current branch
CURRENT_BRANCH=$(git branch --show-current)
echo "📍 Current branch: $CURRENT_BRANCH"

# Reject if on main
if [ "$CURRENT_BRANCH" = "main" ]; then
  echo ""
  echo "❌ Cannot run on main branch!"
  echo "💡 You must bump version in your PR branch before merging."
  echo ""
  echo "Steps:"
  echo "  1. Create or checkout your feature branch"
  echo "  2. Run ./deploy.sh on that branch"
  echo "  3. Commit and push the version bump"
  echo "  4. Merge your PR to main"
  echo ""
  exit 1
fi

# Check for uncommitted changes
if ! git diff-index --quiet HEAD --; then
  echo "❌ You have uncommitted changes. Please commit or stash them first."
  git status --short
  exit 1
fi

# Ask for version bump type
echo ""
echo "Select version bump type:"
echo "  1) patch   (1.43.11 → 1.43.12) - Bug fixes"
echo "  2) minor   (1.43.11 → 1.44.0)  - New features"
echo "  3) major   (1.43.11 → 2.0.0)   - Breaking changes"
echo ""
read -p "Enter choice (1-3): " -n 1 -r
echo ""

case $REPLY in
  1)
    BUMP_TYPE="patch"
    ;;
  2)
    BUMP_TYPE="minor"
    ;;
  3)
    BUMP_TYPE="major"
    ;;
  *)
    echo "❌ Invalid choice"
    exit 1
    ;;
esac

# Show current version
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo ""
echo "📦 Current version: $CURRENT_VERSION"
echo "🔄 Bumping $BUMP_TYPE version..."

# Bump version (this also creates a commit automatically)
npm version $BUMP_TYPE

# Get new version
NEW_VERSION=$(node -p "require('./package.json').version")
echo "✅ New version: $NEW_VERSION"
echo "✅ Version bump committed"
echo ""

# Confirm before pushing
read -p "Push to origin? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "❌ Push cancelled"
  echo "💡 Version is committed locally. Push when ready with: git push"
  exit 1
fi

# Push changes
echo "📤 Pushing to origin/$CURRENT_BRANCH..."
git push origin $CURRENT_BRANCH

echo ""
echo "✨ Done!"
echo "📝 Next steps:"
echo "   1. Merge your PR to main"
echo "   2. release.yml will automatically deploy to npm"
echo ""
echo "🔗 Monitor deployment: https://github.com/MeetElise/chat-ui/actions"
echo ""

