# Fix PATH so pnpm works reliably from VS Code Source Control
export PATH="$(pnpm bin):$PATH"

echo "🔄 Automatically bumping version..."

# Read current version from package.json
CURRENT_VERSION=$(grep '"version"' package.json | head -1 | sed 's/.*"\([^"]*\)".*/\1/')

# Parse version into major, minor, patch
MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
PATCH=$(echo $CURRENT_VERSION | cut -d. -f3)

# Increment patch first
PATCH=$((PATCH + 1))

# Calculate if we need to roll over (every 10 patches)
MINOR_BUMP=$((PATCH / 10))
PATCH=$((PATCH % 10))
MINOR=$((MINOR + MINOR_BUMP))

# Check if minor needs to roll over to major (every 10 minors)
if [ "$MINOR" -ge 10 ]; then
  MAJOR=$((MAJOR + 1))
  MINOR=$((MINOR - 10))
fi

if [ "$MINOR_BUMP" -gt 0 ]; then
  echo "✅ Rolling over: $CURRENT_VERSION → $MAJOR.$MINOR.$PATCH"
else
  echo "✅ Bumping patch: $CURRENT_VERSION → $MAJOR.$MINOR.$PATCH"
fi

NEW_VERSION="$MAJOR.$MINOR.$PATCH"

# Update package.json with new version
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$NEW_VERSION\"/" package.json

# Update pnpm-lock.yaml
pnpm install --lockfile-only

echo "✅ Version updated to $NEW_VERSION"

# Stage the version changes so they become part of this commit
git add package.json pnpm-lock.yaml