#!/bin/bash
# Release script for Aprender
# Generated by bashrs - DO NOT EDIT MANUALLY
# Source: scripts/release.rs

set -euo pipefail

echo "📦 Aprender Release Process"
echo "==========================="
echo ""

VERSION="${1:-}"

if [ -z "$VERSION" ]; then
    echo "Usage: $0 <version>"
    echo "Example: $0 0.1.0"
    exit 1
fi

# Validate version format
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
    echo "❌ Invalid version format: $VERSION"
    echo "   Expected: MAJOR.MINOR.PATCH (e.g., 0.1.0)"
    exit 1
fi

echo "🔖 Preparing release v$VERSION"
echo ""

# Step 1: Run full CI
echo "🧪 [1/6] Running full CI pipeline..."
if ! ./scripts/ci.sh; then
    echo "❌ CI pipeline failed"
    exit 1
fi

# Step 2: Check for uncommitted changes
echo "📋 [2/6] Checking for uncommitted changes..."
if [ -n "$(git status --porcelain)" ]; then
    echo "❌ Uncommitted changes detected"
    git status --short
    exit 1
fi
echo "✅ Working tree clean"

# Step 3: Update version in Cargo.toml
echo "📝 [3/6] Updating version in Cargo.toml..."
sed -i "s/^version = \".*\"/version = \"$VERSION\"/" Cargo.toml
echo "✅ Version updated to $VERSION"

# Step 4: Build release
echo "🔨 [4/6] Building release..."
if ! cargo build --release; then
    echo "❌ Release build failed"
    exit 1
fi
echo "✅ Release build successful"

# Step 5: Create git tag
echo "🏷️  [5/6] Creating git tag..."
git add Cargo.toml
git commit -m "Release v$VERSION"
git tag -a "v$VERSION" -m "Release v$VERSION"
echo "✅ Tag v$VERSION created"

# Step 6: Instructions
echo ""
echo "📋 [6/6] Next steps:"
echo "   1. Review changes: git log --oneline -5"
echo "   2. Push to remote: git push origin main --tags"
echo "   3. Publish to crates.io: cargo publish"
echo ""
echo "🎉 Release v$VERSION prepared successfully!"

exit 0
