#!/bin/bash

# AzureAI Optimizer - Publication Script
# This script builds and publishes the package to npm

set -e  # Exit on any error

echo "🚀 AzureAI Optimizer - Publication Script"
echo "========================================"

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    print_error "package.json not found. Please run this script from the project root."
    exit 1
fi

print_info "Starting publication process..."

# 1. Security Check
echo ""
echo "🔒 Security Check"
echo "=================="

# Check for sensitive data patterns
if grep -r "sk-[a-zA-Z0-9]" src/ config/ --exclude-dir=node_modules 2>/dev/null | grep -v "sk-your" | grep -v "sk-or-v1-your" | grep -v "sk-ant-your"; then
    print_error "Found potential API keys in source code!"
    exit 1
fi

if grep -r "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" src/ config/ --exclude-dir=node_modules 2>/dev/null | grep -v "12345678-1234-1234-1234-123456789012" | grep -v "87654321-4321-4321-4321-210987654321" | grep -v "prod-subscription-id" | grep -v "dev-subscription-id"; then
    print_error "Found potential Azure subscription/tenant IDs in source code!"
    exit 1
fi

print_status "Security check passed - no sensitive data found"

# 2. Package Configuration Check
echo ""
echo "📦 Package Configuration"
echo "======================="

# Check package.json
if ! jq -e '.name == "@azureai/optimizer"' package.json > /dev/null; then
    print_error "Package name is not set to @azureai/optimizer"
    exit 1
fi

if ! jq -e '.bin."azureai-optimizer"' package.json > /dev/null; then
    print_error "Binary entry point not configured"
    exit 1
fi

print_status "Package configuration is correct"

# 3. Build the project
echo ""
echo "🔨 Building Project"
echo "=================="

print_info "Installing dependencies..."
npm install

print_info "Running TypeScript compilation..."
npm run build

if [ ! -d "dist" ]; then
    print_error "Build failed - dist directory not created"
    exit 1
fi

print_status "Build completed successfully"

# 4. Run tests
echo ""
echo "🧪 Running Tests"
echo "==============="

print_info "Running package tests..."
npm test || print_warning "Tests failed or not configured"

print_status "Test phase completed"

# 5. Version check
echo ""
echo "📋 Version Information"
echo "===================="

CURRENT_VERSION=$(jq -r '.version' package.json)
print_info "Current version: $CURRENT_VERSION"

# Check if version exists on npm
if npm view @azureai/optimizer@$CURRENT_VERSION version 2>/dev/null; then
    print_warning "Version $CURRENT_VERSION already exists on npm"
    print_info "Consider bumping the version with: npm version patch|minor|major"
    read -p "Continue with existing version? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# 6. Pre-publication verification
echo ""
echo "🔍 Pre-Publication Verification"
echo "==============================="

# Check if logged into npm
if ! npm whoami > /dev/null 2>&1; then
    print_error "Not logged into npm. Please run 'npm login' first."
    exit 1
fi

NPM_USER=$(npm whoami)
print_info "Logged in as: $NPM_USER"

# Dry run
print_info "Running publication dry run..."
npm publish --dry-run --access public

print_status "Dry run completed successfully"

# 7. Final confirmation
echo ""
echo "🚀 Ready for Publication"
echo "======================="

print_info "Package: @azureai/optimizer@$CURRENT_VERSION"
print_info "NPM User: $NPM_USER"
print_info "Build: ✅ Complete"
print_info "Security: ✅ Verified"

echo ""
read -p "Proceed with publication? (y/N): " -n 1 -r
echo

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    print_info "Publication cancelled by user"
    exit 0
fi

# 8. Publish to npm
echo ""
echo "📤 Publishing to NPM"
echo "==================="

print_info "Publishing package..."
npm publish --access public

print_status "Package published successfully!"

# 9. Verification
echo ""
echo "✅ Post-Publication Verification"
echo "==============================="

print_info "Waiting for npm registry propagation..."
sleep 10

# Verify package is available
if npm view @azureai/optimizer@$CURRENT_VERSION version > /dev/null 2>&1; then
    print_status "Package is available on npm registry"
else
    print_warning "Package not yet available (registry propagation may take a few minutes)"
fi

# Test NPX installation
print_info "Testing NPX installation..."
if npx @azureai/optimizer@$CURRENT_VERSION --version > /dev/null 2>&1; then
    print_status "NPX installation works correctly"
else
    print_warning "NPX installation test failed (may need a few minutes for propagation)"
fi

# 10. Success message
echo ""
echo "🎉 Publication Complete!"
echo "======================="

print_status "AzureAI Optimizer v$CURRENT_VERSION published successfully!"
echo ""
print_info "Users can now install with:"
echo "  npx @azureai/optimizer@latest server start"
echo ""
print_info "MCP Configuration:"
echo '  "command": "npx",'
echo '  "args": ["-y", "@azureai/optimizer@latest", "server", "start"]'
echo ""
print_info "Documentation: https://www.npmjs.com/package/@azureai/optimizer"

echo ""
print_status "🚀 Ready to optimize Azure infrastructure worldwide!"
