#!/bin/bash
# Binder postBuild script (root-level wrapper)
# Binder looks for config at repo root, so we redirect to tinytorch/

set -e

echo "🔧 Setting up TinyTorch from monorepo..."
cd tinytorch

echo "🔧 Installing TinyTorch package..."
pip install -e .

echo ""
echo "📓 Generating student notebooks from source..."
# Convert all src/*.py files to notebooks in modules/
# This ensures students always get fresh notebooks matching the code

for module_dir in src/*/; do
    module_name=$(basename "$module_dir")
    py_file="$module_dir/${module_name}.py"
    # Strip numeric prefix for notebook name (e.g., "01_tensor" -> "tensor")
    short_name="${module_name#*_}"

    if [ -f "$py_file" ]; then
        # Create output directory
        mkdir -p "modules/$module_name"

        # Convert .py to .ipynb using jupytext
        echo "   📝 Converting $module_name..."
        jupytext --to notebook "$py_file" --output "modules/$module_name/${short_name}.ipynb" 2>/dev/null || {
            echo "   ⚠️  Warning: Could not convert $module_name"
        }
    fi
done

echo ""
echo "✅ TinyTorch setup complete!"
echo ""
echo "📚 Available resources:"
echo "   - TinyTorch modules: tinytorch/modules/ (Jupyter notebooks)"
echo "   - Source files: tinytorch/src/ (Python files)"
echo "   - Milestone examples: tinytorch/milestones/"
echo ""
echo "🚀 Start exploring with:"
echo "   - Open any notebook from tinytorch/modules/ in the file browser"
echo "   - Or import tinytorch in a new notebook"
