#!/bin/bash
set -e

# Function to display usage information
function show_usage() {
  echo "Usage: $0 [options]"
  echo ""
  echo "Options:"
  echo "  --help          Show this help message"
  echo "  --no-build      Skip the build step (use existing files)"
  echo "  --dry-run       Perform a dry run without actually publishing"
  echo ""
  echo "Example: ./publish.sh"
}

# Initialize variables
BUILD=true
DRY_RUN=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    --help)
      show_usage
      exit 0
      ;;
    --no-build)
      BUILD=false
      shift
      ;;
    --dry-run)
      DRY_RUN=true
      shift
      ;;
    *)
      echo "Error: Unknown option: $1"
      show_usage
      exit 1
      ;;
  esac
done

# Display header
echo "=== rust-ticker npm package publisher ==="
echo ""

# Build the package if required
if [ "$BUILD" = true ]; then
  echo "Step 1: Building the package..."
  if [ -f "./build.sh" ]; then
    ./build.sh
  else
    echo "Error: build.sh not found in the current directory."
    exit 1
  fi
  echo ""
else
  echo "Step 1: Skipping build (--no-build flag provided)"
  echo ""
fi

# Check that we have the dist/bundler directory
if [ ! -d "dist/bundler" ]; then
  echo "Error: dist/bundler directory not found."
  echo "Please run ./build.sh first."
  exit 1
fi

# Validate the package.json in dist/bundler
echo "Step 2: Validating package.json..."
if command -v node &> /dev/null; then
  if ! node -e "JSON.parse(require('fs').readFileSync('dist/bundler/package.json', 'utf8'))"; then
    echo "Error: Invalid JSON in dist/bundler/package.json"
    exit 1
  fi

  # Check that the package name is rust-ticker
  PKG_NAME=$(node -e "console.log(JSON.parse(require('fs').readFileSync('dist/bundler/package.json', 'utf8')).name)")
  if [ "$PKG_NAME" != "rust-ticker" ]; then
    echo "Error: Package name in dist/bundler/package.json is '$PKG_NAME', not 'rust-ticker'"
    exit 1
  fi

  # Check that the main entry is clockjs.js
  MAIN_ENTRY=$(node -e "console.log(JSON.parse(require('fs').readFileSync('dist/bundler/package.json', 'utf8')).main)")
  if [ "$MAIN_ENTRY" != "clockjs.js" ]; then
    echo "Error: Main entry in dist/bundler/package.json is '$MAIN_ENTRY', not 'clockjs.js'"
    exit 1
  fi

  echo "✅ package.json is valid"
else
  echo "Warning: Node.js not found, skipping package.json validation"
fi
echo ""

# Check that all required files exist
echo "Step 3: Checking for required files..."
REQUIRED_FILES=("clockjs.js" "clock_timer.js" "clock_timer_bg.js" "clock_timer_bg.wasm" "clock_timer.d.ts")
for file in "${REQUIRED_FILES[@]}"; do
  if [ ! -f "dist/bundler/$file" ]; then
    echo "Error: Required file dist/bundler/$file not found"
    exit 1
  fi
done
echo "✅ All required files are present"
echo ""

# Publish the package
echo "Step 4: Publishing the package..."
cd dist/bundler || exit 1

if [ "$DRY_RUN" = true ]; then
  echo "Performing dry run (not actually publishing)..."
  npm publish --dry-run
else
  echo "Publishing to npm..."
  npm publish
fi

# Return to the original directory
cd ../..

echo ""
echo "=== Publishing process complete ==="
