#!/bin/bash

set -e

echo "🚀 Publishing NIA Web Eval Agent MCP Server to npm..."

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found. Run this script from the package root."
    exit 1
fi

# Check if user is logged in to npm
if ! npm whoami > /dev/null 2>&1; then
    echo "❌ Error: Not logged in to npm. Run 'npm login' first."
    exit 1
fi

# Ensure bin files are executable
chmod +x bin/server.js
chmod +x scripts/install-deps.js

# Run tests if they exist
if [ -f "package.json" ] && grep -q '"test"' package.json; then
    echo "🧪 Running tests..."
    npm test
fi

# Build if needed
if [ -f "package.json" ] && grep -q '"build"' package.json; then
    echo "🔨 Building package..."
    npm run build
fi

# Get current version
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo "📦 Current version: $CURRENT_VERSION"

# Ask for version bump
echo "🔢 Choose version bump:"
echo "1) patch (bug fixes)"
echo "2) minor (new features)"
echo "3) major (breaking changes)"
echo "4) custom version"
echo "5) skip version bump"

read -p "Enter choice (1-5): " choice

case $choice in
    1)
        npm version patch
        ;;
    2)
        npm version minor
        ;;
    3)
        npm version major
        ;;
    4)
        read -p "Enter custom version: " custom_version
        npm version $custom_version
        ;;
    5)
        echo "⏭️  Skipping version bump"
        ;;
    *)
        echo "❌ Invalid choice. Exiting."
        exit 1
        ;;
esac

# Get new version
NEW_VERSION=$(node -p "require('./package.json').version")
echo "📦 Publishing version: $NEW_VERSION"

# Publish to npm
echo "📤 Publishing to npm..."
npm publish --access public

echo "✅ Successfully published nia-web-eval-agent-mcp@$NEW_VERSION"
echo "🎉 Users can now install with: npx nia-web-eval-agent-mcp"

# Create git tag if version was bumped
if [ "$NEW_VERSION" != "$CURRENT_VERSION" ]; then
    echo "🏷️  Creating git tag..."
    git tag "v$NEW_VERSION"
    git push origin "v$NEW_VERSION"
    echo "✅ Git tag v$NEW_VERSION created and pushed"
fi

echo ""
echo "📋 Next steps:"
echo "1. Update documentation with new version"
echo "2. Announce on Discord: https://discord.gg/ryjCnf9myb"
echo "3. Update website: https://trynia.ai" 