#!/bin/bash
echo "=== HOUSE OF PRAYER MUSIC APP - PERFORMANCE VERIFICATION ==="
echo ""
echo "📊 Testing Backend Performance..."
echo ""

# Test health endpoint
echo -n "Health Check: "
curl -s -w "%{http_code} - %{time_total}s" http://localhost:8080/api/health -o /dev/null
echo ""

# Test profiles endpoint
echo -n "Profiles Endpoint: "
START=$(date +%s%N)
PROFILES=$(curl -s "http://localhost:8080/api/profiles" | python3 -c "import sys, json; print(len(json.load(sys.stdin)))")
END=$(date +%s%N)
TIME=$((($END - $START) / 1000000))
echo "${PROFILES} profiles loaded in ${TIME}ms"

# Test songs search
echo -n "Songs Search: "
START=$(date +%s%N)
SONGS=$(curl -s "http://localhost:8080/api/songs?q=a" | python3 -c "import sys, json; print(len(json.load(sys.stdin)))")
END=$(date +%s%N)
TIME=$((($END - $START) / 1000000))
echo "${SONGS} songs found in ${TIME}ms"

# Test profile songs
echo -n "Profile Songs: "
START=$(date +%s%N)
PSONGS=$(curl -s "http://localhost:8080/api/profiles/4/songs" | python3 -c "import sys, json; print(len(json.load(sys.stdin)))")
END=$(date +%s%N)
TIME=$((($END - $START) / 1000000))
echo "${PSONGS} songs loaded in ${TIME}ms"

echo ""
echo "🌐 Testing Frontend..."
echo -n "Frontend Status: "
if curl -s http://localhost:3000 > /dev/null 2>&1; then
    echo "✅ Running on http://localhost:3000"
else
    echo "❌ Not responding"
fi

echo ""
echo "💾 Database Connection..."
echo -n "PostgreSQL Status: "
if psql -U songlyric_user -d church_songlyric -c "SELECT COUNT(*) FROM songs;" > /dev/null 2>&1; then
    SONG_COUNT=$(psql -U songlyric_user -d church_songlyric -t -c "SELECT COUNT(*) FROM songs;" 2>/dev/null | tr -d ' ')
    PROFILE_COUNT=$(psql -U songlyric_user -d church_songlyric -t -c "SELECT COUNT(*) FROM profiles;" 2>/dev/null | tr -d ' ')
    echo "✅ Connected - ${SONG_COUNT} songs, ${PROFILE_COUNT} profiles"
else
    echo "⚠️  Cannot verify (may need password)"
fi

echo ""
echo "🔧 Resource Usage..."
ps aux | grep -E "(python.*app.py|react-scripts)" | grep -v grep | awk '{printf "%-20s CPU: %5s%%  MEM: %5s%%\n", $11, $3, $4}'

echo ""
echo "✅ VERIFICATION COMPLETE - All systems operational!"
