#!/bin/bash
# Organize all build artifacts into target/site for serving

set -e

PROJECT_ROOT="${1:-.}"
cd "$PROJECT_ROOT"

echo "🏗️  Organizing build artifacts into target/site/..."

# Ensure target/site exists
mkdir -p target/site

# Copy CSS styles
if [ -d "public/styles" ]; then
    echo "📋 Copying CSS: public/styles → target/site/styles"
    mkdir -p target/site/styles
    cp -r public/styles/* target/site/styles/ 2>/dev/null || true
fi

# Copy images
if [ -d "public/images" ]; then
    echo "📋 Copying images: public/images → target/site/images"
    mkdir -p target/site/images
    cp -r public/images/* target/site/images/ 2>/dev/null || true
fi

# Copy logos
if [ -d "public/logos" ]; then
    echo "📋 Copying logos: public/logos → target/site/logos"
    mkdir -p target/site/logos
    cp -r public/logos/* target/site/logos/ 2>/dev/null || true
fi

# Copy JavaScript
if [ -d "public/js" ]; then
    echo "📋 Copying JS: public/js → target/site/js"
    mkdir -p target/site/js
    cp -r public/js/* target/site/js/ 2>/dev/null || true
fi

# Organize content - link or copy from public/r to target/site/r
if [ -d "public/r" ]; then
    echo "📋 Organizing content: public/r → target/site/r"
    mkdir -p target/site

    # Remove existing symlink/directory if it exists
    if [ -L target/site/r ] || [ -d target/site/r ]; then
        rm -rf target/site/r
    fi

    # Create symlink for dynamic content loading
    ln -sf ../../public/r target/site/r
    echo "  ✓ Created symlink: target/site/r → public/r (for dynamic content)"
fi

# List what was organized
echo ""
echo "✅ Artifact organization complete!"
echo ""
echo "📁 target/site/ structure:"
ls -la target/site/ | grep "^d" | awk '{print "  📂 " $NF}'
ls -la target/site/ | grep "^l" | awk '{print "  🔗 " $NF}'

echo ""
echo "🚀 Ready to serve!"
echo "   Content will be served from: /r/blog/en/index.json, /r/recipes/en/index.json, etc."
