#!/bin/bash
# safe_test.sh - Exécute les tests UN PAR UN avec pause entre chaque
# Usage: ./scripts/safe_test.sh [package_pattern]

set -e

cd "$(dirname "$0")/.."

PATTERN="${1:-./internal/...}"
PAUSE_SECONDS=2

echo "=== TESTS SÉCURISÉS (Anti-OOM) ==="
echo "Pattern: $PATTERN"
echo "Pause entre packages: ${PAUSE_SECONDS}s"
echo ""

# Lister les packages
PACKAGES=$(go list $PATTERN 2>/dev/null || echo "")

if [ -z "$PACKAGES" ]; then
    echo "❌ Aucun package trouvé pour: $PATTERN"
    exit 1
fi

TOTAL=$(echo "$PACKAGES" | wc -l)
CURRENT=0
PASSED=0
FAILED=0
SKIPPED=0

for pkg in $PACKAGES; do
    CURRENT=$((CURRENT + 1))
    SHORT_NAME=$(echo "$pkg" | sed 's|.*/internal/||')
    
    echo -n "[$CURRENT/$TOTAL] $SHORT_NAME ... "
    
    # Exécuter le test avec timeout
    RESULT=$(timeout 60s go test -count=1 -cover "$pkg" 2>&1) || true
    
    if echo "$RESULT" | grep -q "no test files"; then
        echo "⏭️  NO TESTS"
        SKIPPED=$((SKIPPED + 1))
    elif echo "$RESULT" | grep -q "FAIL"; then
        echo "❌ FAIL"
        FAILED=$((FAILED + 1))
        echo "   $RESULT" | tail -3
    elif echo "$RESULT" | grep -q "ok"; then
        COV=$(echo "$RESULT" | grep -oP 'coverage: \K[0-9.]+' || echo "?")
        echo "✅ PASS (${COV}%)"
        PASSED=$((PASSED + 1))
    else
        echo "⚠️  UNKNOWN"
        SKIPPED=$((SKIPPED + 1))
    fi
    
    # PAUSE OBLIGATOIRE pour libérer la RAM
    sleep $PAUSE_SECONDS
done

echo ""
echo "=== RÉSUMÉ ==="
echo "✅ Passés: $PASSED"
echo "❌ Échoués: $FAILED"
echo "⏭️  Sans tests: $SKIPPED"
echo "📊 Total: $TOTAL packages"

