#!/usr/bin/env bash
# version-bump.sh — Bump version across all workspace packages
#
# Usage:
#   scripts/version-bump.sh <new-version>
#   scripts/version-bump.sh 0.0.21
#
# Enforces:
#   - Version MUST be 0.0.x (alpha constraint)
#   - All package.json files are updated atomically
#   - Rejects 0.1.0+ until explicitly unlocked

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

if [[ $# -ne 1 ]]; then
  echo "Usage: $0 <version>"
  echo "Example: $0 0.0.21"
  exit 1
fi

NEW_VERSION="$1"

# Hard gate: alpha constraint (0.0.x only)
if [[ ! "$NEW_VERSION" =~ ^0\.0\.[0-9]+$ ]]; then
  echo "ERROR: Version must be 0.0.x (alpha). Got: $NEW_VERSION"
  echo ""
  echo "This project is in ALPHA. Versions >= 0.1.0 are not allowed."
  echo "If this constraint needs to change, update AGENTS.md and this script."
  exit 1
fi

# Patch number must be > 0
PATCH="${NEW_VERSION##0.0.}"
if [[ "$PATCH" -lt 1 ]]; then
  echo "ERROR: Patch version must be >= 1. Got: $NEW_VERSION"
  exit 1
fi

# Find all package.json files in the monorepo
PACKAGE_FILES=(
  "$REPO_ROOT/package.json"
)

for dir in "$REPO_ROOT"/apps/*/package.json "$REPO_ROOT"/packages/*/package.json; do
  [[ -f "$dir" ]] && PACKAGE_FILES+=("$dir")
done

echo "Bumping all packages to $NEW_VERSION"
echo ""

for pkg in "${PACKAGE_FILES[@]}"; do
  REL_PATH="${pkg#"$REPO_ROOT"/}"
  OLD_VERSION=$(grep -o '"version": "[^"]*"' "$pkg" | head -1 | cut -d'"' -f4)
  # Use node for reliable JSON editing (preserves formatting better than sed)
  node -e "
    const fs = require('fs');
    const path = '$pkg';
    const raw = fs.readFileSync(path, 'utf8');
    const updated = raw.replace(/\"version\": \"[^\"]*\"/, '\"version\": \"$NEW_VERSION\"');
    fs.writeFileSync(path, updated);
  "
  echo "  $REL_PATH: $OLD_VERSION -> $NEW_VERSION"
done

echo ""
echo "Done. $NEW_VERSION applied to ${#PACKAGE_FILES[@]} packages."
echo "Next steps: commit, tag (v$NEW_VERSION), push."
