#!/bin/bash
set -e

# Release script for the Legion Protocol ecosystem
# Usage: ./release.sh [phalanx|legion-protocol|centurion|legionnaire] [version]

COMPONENT=$1
VERSION=$2

if [ -z "$COMPONENT" ] || [ -z "$VERSION" ]; then
    echo "Usage: $0 [phalanx|legion-protocol|centurion|legionnaire] [version]"
    echo "Example: $0 phalanx 0.1.0"
    exit 1
fi

# Validate version format
if ! [[ $VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Error: Version must be in format X.Y.Z (e.g., 0.1.0)"
    exit 1
fi

# Set component directory
case $COMPONENT in
    phalanx)
        DIR="phalanx"
        ;;
    legion-protocol)
        DIR="legion-protocol"
        ;;
    centurion|legion-server)
        DIR="centurion"
        ;;
    legionnaire)
        DIR="legionnaire"
        ;;
    *)
        echo "Error: Unknown component '$COMPONENT'"
        echo "Valid components: phalanx, legion-protocol, centurion, legion-server, legionnaire"
        exit 1
        ;;
esac

echo "🚀 Releasing $COMPONENT v$VERSION"

# Change to component directory
cd "$DIR"

# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

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

# Update version in Cargo.toml
echo "📝 Updating version in Cargo.toml..."
sed -i.bak "s/^version = \".*\"/version = \"$VERSION\"/" Cargo.toml
rm -f Cargo.toml.bak

# Run tests
echo "🧪 Running tests..."
cargo test --all-features

# Run cargo check
echo "🔍 Running cargo check..."
cargo check --all-features

# Commit version bump
echo "📦 Committing version bump..."
git add Cargo.toml
git commit -m "bump: Release $COMPONENT v$VERSION"

# Create and push tag
echo "🏷️  Creating and pushing tag..."
git tag "v$VERSION"
git push origin main
git push origin "v$VERSION"

echo "✅ Release process initiated for $COMPONENT v$VERSION"
echo "📋 GitHub Actions will now:"
echo "   - Run tests"
echo "   - Publish to crates.io"
if [ "$COMPONENT" = "legionnaire" ]; then
    echo "   - Build release binaries"
    echo "   - Create GitHub release with binaries"
fi
echo ""
echo "🔗 Monitor the release at: https://github.com/exec/$DIR/actions"