#!/bin/bash

# Diagrammers API Publishing Script
echo "🚀 Publishing Diagrammers API..."

# Check if user is logged into npm
if ! npm whoami &> /dev/null; then
    echo "❌ You need to be logged into npm. Run: npm login"
    exit 1
fi

# Build the project first
echo "🔧 Building API..."
npm run build:prod

# Check if lib directory was created
if [ ! -d "lib" ]; then
    echo "❌ Build failed - lib directory not found"
    exit 1
fi

# Check if package.json is properly configured
if ! grep -q '"name": "@diagramers/api"' package.json; then
    echo "❌ Package name not set correctly in package.json"
    exit 1
fi

# Check if version is set
if ! grep -q '"version":' package.json; then
    echo "❌ Version not set in package.json"
    exit 1
fi

# Show what will be published
echo "📦 Files that will be published:"
npm pack --dry-run

echo ""
echo "📁 Built files in lib directory:"
ls -la lib/

echo ""
echo "⚠️  Review the files above. Continue with publishing? (y/N)"
read -r response

if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    echo "🚀 Publishing to npm..."
    npm publish --access public
    
    if [ $? -eq 0 ]; then
        echo "✅ Successfully published to npm!"
        echo ""
        echo "🎉 Users can now install your API package with:"
        echo "   npm install @diagramers/api"
        echo ""
        echo "📚 Or use it in their projects:"
        echo "   import { DiagramersAPI } from '@diagramers/api'"
    else
        echo "❌ Failed to publish to npm"
        exit 1
    fi
else
    echo "❌ Publishing cancelled"
    exit 1
fi
