#!/bin/bash

echo "🚀 Publishing Citrea Agent Kit SDK to npm..."
echo ""

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

echo "✅ Logged in as: $(npm whoami)"
echo ""

# Check if package name is available
echo "🔍 Checking package name availability..."
if npm view citrea-agent-kit &> /dev/null; then
    echo "❌ Package 'citrea-agent-kit' already exists on npm"
    echo "💡 You may need to choose a different name or update the version"
    exit 1
else
    echo "✅ Package name 'citrea-agent-kit' is available"
fi

echo ""

# Build the package
echo "🔨 Building package..."
npm run build

if [ $? -ne 0 ]; then
    echo "❌ Build failed. Please fix errors before publishing."
    exit 1
fi

echo "✅ Build successful"
echo ""

# Show what will be published
echo "📦 Package contents:"
npm pack --dry-run | head -20
echo "..."

# Confirm before publishing
echo ""
read -p "🤔 Do you want to publish citrea-agent-kit@0.0.1 to npm? (y/N): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "🚀 Publishing to npm..."
    npm publish
    
    if [ $? -eq 0 ]; then
        echo ""
        echo "🎉 SUCCESS! Your package has been published!"
        echo ""
        echo "📦 Package: https://www.npmjs.com/package/citrea-agent-kit"
        echo "📚 Install: npm install citrea-agent-kit"
        echo ""
        echo "🔍 Verify: npm view citrea-agent-kit"
    else
        echo "❌ Publishing failed. Check the error messages above."
        exit 1
    fi
else
    echo "❌ Publishing cancelled."
    exit 0
fi
