#!/bin/bash
# Generate documentation media from example programs.
#
# Usage: ./scripts/generate-doc-images.sh
#
# This script runs all `doc_*.rs` examples plus the animation gallery generator
# so the static images and GIFs cited by rustdoc/README stay in sync with
# `docs/assets/rustdoc/`.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
IMAGES_DIR="$PROJECT_ROOT/docs/assets/rustdoc"

# Ensure the asset directory exists
mkdir -p "$IMAGES_DIR"

echo "Generating documentation images..."
echo "Output directory: $IMAGES_DIR"
echo ""

# Track statistics
total=0
success=0
failed=0

run_example() {
    local name="$1"
    local features="${2:-}"

    total=$((total + 1))
    echo "[$total] Generating: $name"

    local cmd=(cargo run --example "$name" --release)
    if [ -n "$features" ]; then
        cmd+=(--features "$features")
    fi

    if "${cmd[@]}" 2>&1; then
        success=$((success + 1))
        echo "    ✓ Success"
    else
        failed=$((failed + 1))
        echo "    ✗ Failed"
    fi
    echo ""
}

# Find all doc_*.rs examples in the examples directory
for example in "$PROJECT_ROOT"/examples/doc_*.rs; do
    if [ ! -f "$example" ]; then
        echo "No doc_*.rs examples found in examples/"
        exit 0
    fi

    name=$(basename "$example" .rs)

    case "$name" in
        doc_typst_text)
            run_example "$name" "typst-math"
            ;;
        *)
            run_example "$name"
            ;;
    esac
done

run_example "generate_animation_gallery" "animation"

echo "================================"
echo "Summary: $success/$total succeeded"
if [ $failed -gt 0 ]; then
    echo "Warning: $failed examples failed"
    exit 1
fi
echo "Done. Images saved to $IMAGES_DIR"
