#!/bin/bash
set -e

echo "🚀 MCP Gateway CLI Release Script"
echo ""

# Get version
VERSION=${1:-"0.1.0"}
echo "📦 Version: $VERSION"
echo ""

# Confirm
read -p "Ready to release v$VERSION? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Aborted"
    exit 1
fi

cd "$(dirname "$0")"

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

# Clean previous builds
echo "🧹 Cleaning..."
make clean

# Build
echo "🔨 Building package..."
python -m build

# Get SHA256 for Homebrew
echo ""
echo "📊 Package built! SHA256:"
SHA256=$(shasum -a 256 dist/mcpgw-${VERSION}.tar.gz | awk '{print $1}')
echo "$SHA256"
echo ""

# Update Homebrew formula
echo "📝 Updating Homebrew formula..."
sed -i.bak "s|url \".*\"|url \"https://files.pythonhosted.org/packages/source/m/mcpgw/mcpgw-${VERSION}.tar.gz\"|" mcpgw.rb
sed -i.bak "s/sha256 \".*\"/sha256 \"$SHA256\"/" mcpgw.rb
rm mcpgw.rb.bak

# Commit changes
echo "💾 Committing version bump..."
git add pyproject.toml mcpgw.rb
git commit -m "Release v$VERSION"

# Create tag
echo "🏷️  Creating git tag..."
git tag -a "v$VERSION" -m "Release v$VERSION"

echo ""
echo "✅ Ready to publish!"
echo ""
echo "Next steps:"
echo "  1. git push origin main"
echo "  2. git push origin v$VERSION"
echo "  3. Create GitHub release (triggers PyPI publish)"
echo "  4. python -m twine upload dist/* (or wait for GitHub Action)"
echo ""
echo "For Homebrew:"
echo "  5. Copy mcpgw.rb to homebrew-tap/Formula/"
echo "  6. Push to homebrew-tap repo"
echo ""
