#!/bin/bash
set -e

echo "📦 Bundling React app to single HTML artifact..."

if ! command -v pnpm >/dev/null 2>&1; then
  echo "pnpm is required; install it explicitly before exporting." >&2
  exit 1
fi
if [ -e bundle.html ]; then
  echo "bundle.html already exists; move it aside before exporting." >&2
  exit 1
fi

# Check if we're in a project directory
if [ ! -f "package.json" ]; then
  echo "❌ Error: No package.json found. Run this script from your project root."
  exit 1
fi

# Check if index.html exists
if [ ! -f "index.html" ]; then
  echo "❌ Error: No index.html found in project root."
  echo "   This script requires an index.html entry point."
  exit 1
fi

# Install bundling dependencies
echo "📦 Installing bundling dependencies..."
pnpm add -D parcel @parcel/config-default parcel-resolver-tspaths html-inline

# Create Parcel config with tspaths resolver
if [ ! -f ".parcelrc" ]; then
  echo "🔧 Creating Parcel configuration with path alias support..."
  cat > .parcelrc << 'EOF'
{
  "extends": "@parcel/config-default",
  "resolvers": ["parcel-resolver-tspaths", "..."]
}
EOF
fi

# Never erase an existing app's dist or replace a previous delivery implicitly.
ARTIFACT_BUILD_DIR=$(mktemp -d .artifact-build.XXXXXX)

# Build with Parcel
echo "🔨 Building with Parcel..."
pnpm exec parcel build index.html --dist-dir "$ARTIFACT_BUILD_DIR" --no-source-maps

# Inline everything into single HTML
echo "🎯 Inlining all assets into single HTML file..."
pnpm exec html-inline "$ARTIFACT_BUILD_DIR/index.html" > "$ARTIFACT_BUILD_DIR/bundle.html"
mv "$ARTIFACT_BUILD_DIR/bundle.html" bundle.html

# Get file size
FILE_SIZE=$(du -h bundle.html | cut -f1)

echo ""
echo "✅ Bundle complete!"
echo "📄 Output: bundle.html ($FILE_SIZE)"
echo ""
echo "You can now open bundle.html directly in your browser to view the artifact."
