#!/bin/bash
# Détecte les tests lents (T0050)

set -e

THRESHOLD="${TEST_PERFORMANCE_THRESHOLD:-5s}"
PACKAGE="${1:-./...}"

echo "🔍 Analyzing test performance for: $PACKAGE"
echo "⏱️  Threshold: $THRESHOLD"
echo ""

# Fonction pour convertir durée en secondes (gère format go test: 1.234s, 0.123s, etc.)
duration_to_seconds() {
	local duration="$1"
	# Enlever le 's' à la fin et convertir en float
	echo "$duration" | sed 's/s$//'
}

# Fonction pour comparer deux durées
compare_durations() {
	local duration1=$(duration_to_seconds "$1")
	local threshold=$(duration_to_seconds "$2")
	
	# Utiliser awk pour comparer les floats
	awk -v d1="$duration1" -v th="$threshold" 'BEGIN { if (d1 > th) exit 0; else exit 1 }'
}

# Compteurs
slow_tests=0
total_tests=0
total_duration=0

# Exécuter les tests et analyser les résultats
go test "$PACKAGE" -json 2>/dev/null | while IFS= read -r line; do
	# Parser la sortie JSON avec grep et sed (fallback si jq n'est pas disponible)
	if command -v jq >/dev/null 2>&1; then
		action=$(echo "$line" | jq -r '.Action // empty' 2>/dev/null || true)
		test_name=$(echo "$line" | jq -r '.Test // empty' 2>/dev/null || true)
		elapsed=$(echo "$line" | jq -r '.Elapsed // empty' 2>/dev/null || true)
		package_name=$(echo "$line" | jq -r '.Package // empty' 2>/dev/null || true)
	else
		# Fallback: parser manuellement avec grep/sed
		if echo "$line" | grep -q '"Action"'; then
			action=$(echo "$line" | grep -o '"Action":"[^"]*"' | sed 's/"Action":"\([^"]*\)"/\1/')
			test_name=$(echo "$line" | grep -o '"Test":"[^"]*"' | sed 's/"Test":"\([^"]*\)"/\1/' || echo "")
			elapsed=$(echo "$line" | grep -o '"Elapsed":[0-9.]*' | sed 's/"Elapsed":\([0-9.]*\)/\1/' || echo "")
			package_name=$(echo "$line" | grep -o '"Package":"[^"]*"' | sed 's/"Package":"\([^"]*\)"/\1/' || echo "")
		else
			continue
		fi
	fi

	if [ -z "$action" ]; then
		continue
	fi

	# Compter les tests passés/échoués
	if [ "$action" = "pass" ] || [ "$action" = "fail" ]; then
		if [ -n "$test_name" ] && [ -n "$elapsed" ]; then
			total_tests=$((total_tests + 1))
			
			# Ajouter 's' si manquant
			if ! echo "$elapsed" | grep -q 's$'; then
				elapsed="${elapsed}s"
			fi
			
			# Vérifier si le test est lent
			if compare_durations "$elapsed" "$THRESHOLD"; then
				echo "⚠️  SLOW TEST: ${package_name}/${test_name} took ${elapsed}"
				slow_tests=$((slow_tests + 1))
			fi
			
			# Accumuler la durée totale (en secondes)
			duration_sec=$(duration_to_seconds "$elapsed")
			total_duration=$(awk -v d1="$total_duration" -v d2="$duration_sec" 'BEGIN { printf "%.3f", d1 + d2 }')
		fi
	fi
done

# Afficher le résumé
echo ""
echo "📊 Summary:"
echo "   Total tests: $total_tests"
echo "   Slow tests (>$THRESHOLD): $slow_tests"
if [ "$total_tests" -gt 0 ]; then
	avg_duration=$(awk -v total="$total_duration" -v count="$total_tests" 'BEGIN { printf "%.3f", total / count }')
	echo "   Average duration: ${avg_duration}s"
	echo "   Total duration: ${total_duration}s"
fi

# Retourner code d'erreur si des tests lents ont été détectés
if [ "$slow_tests" -gt 0 ]; then
	echo ""
	echo "❌ Found $slow_tests slow test(s) exceeding threshold of $THRESHOLD"
	exit 1
else
	echo ""
	echo "✅ All tests completed within threshold of $THRESHOLD"
	exit 0
fi

