#!/bin/bash
set -e  # Exit on any error

echo "Building build.valuecurve.co..."

# Clean dist
rm -rf dist
mkdir -p dist

# 1. Build SvelteKit homepage
echo "Building homepage..."
(cd apps/homepage && npm run build)

# 2. Copy SvelteKit build (base site + listing pages)
echo "Copying SvelteKit build..."
cp -r apps/homepage/build/* dist/

# 3. Build flowchart app
echo "Building flowchart..."
(cd apps/flowchart && npm run build)

# 4. Merge flowchart into tools/flowchart/
mkdir -p dist/tools/flowchart
cp -r apps/flowchart/dist/* dist/tools/flowchart/

# 5. Build Quarto guide (if quarto is available)
if command -v quarto &> /dev/null; then
    echo "Building statistical-tests guide..."
    quarto render posts/statistical-tests.qmd
    mkdir -p dist/guides/statistical-tests
    cp _site/posts/statistical-tests.html dist/guides/statistical-tests/index.html
else
    echo "Quarto not found, copying pre-built guide..."
    if [ -d "guides/statistical-tests" ]; then
        cp -r guides/statistical-tests dist/guides/
    fi
fi

echo ""
echo "Build complete!"
echo ""
echo "dist/ contents:"
ls -la dist/
echo ""
echo "guides/:"
ls -la dist/guides/ 2>/dev/null || echo "  (none)"
echo ""
echo "tools/:"
ls -la dist/tools/ 2>/dev/null || echo "  (none)"
echo ""
echo "To deploy: ./scripts/deploy.sh"
