#!/bin/bash

# BMAD Enhanced - Beta Publishing Script
# Publishes beta versions to NPM with pre-release tag

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${BLUE}🚀 BMAD Enhanced - Beta Publishing${NC}"
echo "===================================="
echo ""

# First run pre-publish validation
echo -e "${YELLOW}📋 Running pre-publish validation...${NC}"
if ! bash ck-layer/scripts/03-pre-publish-validation.sh; then
    echo -e "${RED}❌ Pre-publish validation failed!${NC}"
    echo "Please fix the issues before publishing."
    exit 1
fi

echo -e "${GREEN}✅ Pre-publish validation passed!${NC}"
echo ""

# Load environment variables from .env
if [ -f .env ]; then
    export $(grep -v '^#' .env | xargs)
    echo "✅ Loaded environment variables from .env"
else
    echo "❌ Error: .env file not found"
    echo "   Please create .env with NPM_TOKEN=your_token"
    exit 1
fi

# Check if NPM_TOKEN exists
if [ -z "$NPM_TOKEN" ]; then
    echo "❌ Error: NPM_TOKEN not found in .env file"
    echo "   Please add NPM_TOKEN=your_token to .env"
    exit 1
fi

echo "✅ NPM token found in environment"

# Get current version from package.json
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo "📦 Current version: $CURRENT_VERSION"

# Create beta version (append -beta.timestamp if not already beta)
if [[ $CURRENT_VERSION == *"-beta"* ]]; then
    # Already a beta version, use as-is
    BETA_VERSION="$CURRENT_VERSION"
    echo "📦 Using existing beta version: $BETA_VERSION"
else
    # Not a beta version, append beta timestamp
    BETA_VERSION="${CURRENT_VERSION}-beta.$(date +%Y%m%d%H%M%S)"
    echo "🔄 Creating beta version: $BETA_VERSION"
fi

# Temporarily update package.json version (only if needed)
if [ "$BETA_VERSION" != "$CURRENT_VERSION" ]; then
    echo "📝 Updating package.json with beta version..."
    node -e "
    const fs = require('fs');
    const pkg = require('./package.json');
    pkg.version = '$BETA_VERSION';
    fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
    "
fi

# Set npm auth token
npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN

# Publish beta
echo "🚀 Publishing beta version to NPM..."
npm publish --tag beta --access public

# Restore original version (only if we changed it)
if [ "$BETA_VERSION" != "$CURRENT_VERSION" ]; then
    echo "🔄 Restoring original package.json version..."
    node -e "
    const fs = require('fs');
    const pkg = require('./package.json');
    pkg.version = '$CURRENT_VERSION';
    fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
    "
fi

echo ""
echo -e "${GREEN}✅ Beta published successfully!${NC}"
echo "📦 Package: @cloudkinetix/bmad-enhanced@$BETA_VERSION"
echo "🏷️  Tag: beta"
echo ""
echo "To install beta version:"
echo "  npm install @cloudkinetix/bmad-enhanced@beta"
echo "  npx @cloudkinetix/bmad-enhanced@beta install"
echo ""
echo "Next step: Test the beta version before publishing stable"
echo "When ready, run: npm run publish:stable"