#!/bin/bash

# onepm Cursor MCP Publishing Script
set -e

echo "🚀 Publishing onepm Cursor MCP to npm"
echo "====================================="

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    echo "❌ Error: Please run this script from the onepm-cursor-mcp directory"
    exit 1
fi

# Check if npm is logged in
if ! npm whoami &> /dev/null; then
    echo "❌ Error: Please log in to npm first with 'npm login'"
    exit 1
fi

echo "✅ npm login verified"

# Clean and build
echo "🧹 Cleaning previous build..."
npm run clean

echo "📦 Installing dependencies..."
npm install

echo "🔨 Building project..."
npm run build

# Check if dist directory exists and has files
if [ ! -d "dist" ] || [ -z "$(ls -A dist)" ]; then
    echo "❌ Error: Build failed - dist directory is empty"
    exit 1
fi

echo "✅ Build completed successfully"

# Make sure the main entry point is executable
chmod +x dist/index.js

# Run any pre-publish checks
echo "🧪 Running pre-publish checks..."

# Check package.json validity
npm run prepublishOnly

# Test the package locally
echo "🧪 Testing package installation..."
npm pack --dry-run

# Prompt for version bump
echo ""
echo "Current version: $(node -p "require('./package.json').version")"
echo ""
read -p "Do you want to bump the version? (patch/minor/major/none) [none]: " version_bump

if [ "$version_bump" != "none" ] && [ "$version_bump" != "" ]; then
    if [ "$version_bump" == "patch" ] || [ "$version_bump" == "minor" ] || [ "$version_bump" == "major" ]; then
        npm version $version_bump
        echo "✅ Version bumped to $(node -p "require('./package.json').version")"
    else
        echo "⚠️  Invalid version bump option, skipping..."
    fi
fi

# Final confirmation
echo ""
echo "📋 Package Summary:"
echo "Name: $(node -p "require('./package.json').name")"
echo "Version: $(node -p "require('./package.json').version")"
echo "Description: $(node -p "require('./package.json').description")"
echo ""

read -p "Ready to publish to npm? (y/N): " confirm

if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    echo "❌ Publishing cancelled"
    exit 1
fi

# Publish to npm
echo "🚀 Publishing to npm..."
npm publish

echo ""
echo "🎉 Successfully published to npm!"
echo ""
echo "📋 Users can now install with:"
echo "   npm install -g onepm-cursor-mcp"
echo ""
echo "🔧 Or run directly with:"
echo "   npx onepm-cursor-mcp configure"
echo ""
echo "📚 Don't forget to:"
echo "   - Update documentation with the new version"
echo "   - Create a GitHub release"
echo "   - Announce the release to users"