#!/bin/bash

echo "🚀 Publishing Breathe HR MCP Server to npm"
echo "========================================="

# Check if logged in to npm
echo "📝 Checking npm login status..."
npm whoami &> /dev/null
if [ $? -ne 0 ]; then
    echo "❌ Not logged in to npm. Please run: npm login"
    exit 1
fi

# Clean and build
echo "🧹 Cleaning previous build..."
rm -rf dist/

echo "🔨 Building project..."
npm run build
if [ $? -ne 0 ]; then
    echo "❌ Build failed!"
    exit 1
fi

# Test the build
echo "✅ Build successful!"

# Check package name availability
echo "🔍 Checking package name availability..."
npm view breathe-api &> /dev/null
if [ $? -eq 0 ]; then
    echo "⚠️  Package name 'breathe-api' already exists on npm!"
    echo "   Current version on npm: $(npm view breathe-api version)"
    echo "   Your version: $(node -p "require('./package.json').version")"
    echo ""
    read -p "Continue with publish? (y/n) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Dry run
echo "🧪 Running publish dry-run..."
npm publish --dry-run

echo ""
read -p "📦 Ready to publish? (y/n) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    npm publish
    echo "✨ Published successfully!"
    echo ""
    echo "Next steps:"
    echo "1. Test installation: npm install -g breathe-api"
    echo "2. Create GitHub release: git tag v$(node -p "require('./package.json').version")"
    echo "3. Push tags: git push --tags"
else
    echo "❌ Publish cancelled"
fi