#!/bin/bash
# safe_coverage.sh - Mesure la couverture UN PACKAGE À LA FOIS
# Usage: ./scripts/safe_coverage.sh

set -e

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

echo "=== COUVERTURE SÉCURISÉE (Anti-OOM) ==="
echo ""

RESULTS_FILE="/tmp/veza_coverage_$(date +%s).txt"
> "$RESULTS_FILE"

PACKAGES=$(go list ./internal/... 2>/dev/null)
TOTAL=$(echo "$PACKAGES" | wc -l)
CURRENT=0

TOTAL_COV=0
COV_COUNT=0

for pkg in $PACKAGES; do
    CURRENT=$((CURRENT + 1))
    SHORT_NAME=$(echo "$pkg" | sed 's|.*/internal/||')
    
    # Test avec couverture (timeout 60s, silencieux)
    COV=$(timeout 60s go test -count=1 -cover "$pkg" 2>/dev/null | grep -oP 'coverage: \K[0-9.]+' || echo "")
    
    if [ -n "$COV" ]; then
        printf "%-50s %6s%%\n" "$SHORT_NAME" "$COV"
        echo "$SHORT_NAME|$COV" >> "$RESULTS_FILE"
        TOTAL_COV=$(echo "$TOTAL_COV + $COV" | bc)
        COV_COUNT=$((COV_COUNT + 1))
    else
        printf "%-50s %6s\n" "$SHORT_NAME" "N/A"
    fi
    
    # PAUSE pour libérer RAM
    sleep 1
done

echo ""
echo "=== STATISTIQUES ==="

if [ $COV_COUNT -gt 0 ]; then
    AVG=$(echo "scale=2; $TOTAL_COV / $COV_COUNT" | bc)
    echo "📊 Moyenne: $AVG%"
    echo "📦 Packages testés: $COV_COUNT / $TOTAL"
    
    if (( $(echo "$AVG >= 85" | bc -l) )); then
        echo "✅ OBJECTIF 85% ATTEINT!"
    else
        DELTA=$(echo "scale=2; 85 - $AVG" | bc)
        echo "❌ Il manque $DELTA% pour atteindre 85%"
    fi
else
    echo "⚠️  Aucun package avec couverture mesurable"
fi

echo ""
echo "Résultats sauvés dans: $RESULTS_FILE"

