#!/bin/bash
# Re-transpile all Python examples that have corresponding .rs files

set -e

DEPYLER_BIN="./target/debug/depyler"

# Check if depyler binary exists
if [ ! -f "$DEPYLER_BIN" ]; then
    echo "❌ Error: depyler binary not found at $DEPYLER_BIN"
    echo "Run: cargo build -p depyler"
    exit 1
fi

# Find all .rs files with transpilation headers
echo "🔍 Finding transpiled .rs files..."
RS_FILES=$(find ./examples -name "*.rs" -type f -exec grep -l "Generated by: depyler" {} \; 2>/dev/null || true)

if [ -z "$RS_FILES" ]; then
    echo "❌ No transpiled .rs files found"
    exit 1
fi

TOTAL=$(echo "$RS_FILES" | wc -l | tr -d ' ')
echo "📦 Found $TOTAL transpiled files to regenerate"
echo ""

SUCCESS=0
FAILED=0
SKIPPED=0

for rs_file in $RS_FILES; do
    # Convert .rs to .py
    py_file="${rs_file%.rs}.py"

    if [ ! -f "$py_file" ]; then
        echo "⊘  Skipping $rs_file (no .py source)"
        SKIPPED=$((SKIPPED + 1))
        continue
    fi

    echo -n "🔄 Transpiling $(basename $py_file) ... "

    # Run transpiler with -o flag
    if $DEPYLER_BIN transpile "$py_file" -o "$rs_file.tmp" >/dev/null 2>&1; then
        # Add header comment
        {
            echo "// Generated by: depyler transpile $py_file"
            echo "// Source: $py_file"
            echo "// Command: depyler transpile $py_file"
            echo ""
            cat "$rs_file.tmp"
        } > "$rs_file"
        rm "$rs_file.tmp"
        echo "✅"
        SUCCESS=$((SUCCESS + 1))
    else
        echo "❌"
        rm -f "$rs_file.tmp"
        FAILED=$((FAILED + 1))
    fi
done

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📊 Re-transpilation Summary"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "   ✅ Success: $SUCCESS"
echo "   ❌ Failed:  $FAILED"
echo "   ⊘  Skipped: $SKIPPED"
echo "   📦 Total:   $TOTAL"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ $FAILED -gt 0 ]; then
    exit 1
fi
