#!/bin/bash

# Hyly E2E Plugin - Publishing Script (Unix/Mac)

set -e  # Exit on error

echo "====================================================="
echo "  Publishing Hyly E2E Plugin to NPM"
echo "====================================================="
echo ""

# Check if logged in to NPM
echo "Checking NPM login status..."
if ! npm whoami &> /dev/null; then
    echo ""
    echo "❌ ERROR: You are not logged in to NPM"
    echo "Please run: npm login"
    exit 1
fi

echo "✅ Logged in to NPM as:"
npm whoami
echo ""

# Verify package
echo "Verifying package structure..."
if ! node index.js; then
    echo ""
    echo "❌ ERROR: Package verification failed"
    exit 1
fi
echo ""

# Show what will be published
echo "Checking package contents..."
npm pack --dry-run
echo ""

# Ask for confirmation
read -p "Ready to publish? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Publishing cancelled"
    exit 0
fi

# Publish to NPM
echo ""
echo "Publishing to NPM..."
if ! npm publish; then
    echo ""
    echo "❌ ERROR: Publishing failed"
    exit 1
fi

# Get version
version=$(node -p "require('./package.json').version")

echo ""
echo "====================================================="
echo "  ✅ Successfully published version $version!"
echo "====================================================="
echo ""
echo "View your package at:"
echo "https://www.npmjs.com/package/hyly-e2e-plugin"
echo ""
echo "Users can now install with:"
echo "  npm install -g hyly-e2e-plugin"
echo "  /plugin install hyly-e2e-plugin"
echo ""
