#!/bin/bash
# Complete Services Loading Test - Frontend + Backend

echo "╔════════════════════════════════════════════════════════╗"
echo "║     Services Loading Complete Diagnostic              ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

# 1. Backend API Test
echo "🔹 Backend Services API:"
BACKEND_RESPONSE=$(curl -s http://localhost:8181/api/services)
BACKEND_COUNT=$(echo "$BACKEND_RESPONSE" | python3 -c 'import sys,json; print(len(json.load(sys.stdin)))' 2>/dev/null || echo "ERROR")

if [ "$BACKEND_COUNT" = "ERROR" ]; then
    echo "   ❌ Backend API Error"
    echo "   Response: $BACKEND_RESPONSE"
else
    echo "   ✅ Backend API: $BACKEND_COUNT services"
    echo "   Sample services:"
    echo "$BACKEND_RESPONSE" | python3 -c 'import sys,json; [print(f"      • {s[\"name\"]} ({s[\"category\"]}) - ${s[\"price\"]}") for s in json.load(sys.stdin)[:3]]' 2>/dev/null
fi
echo ""

# 2. Frontend Status
echo "🔹 Frontend Status:"
FRONTEND_HTTP=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:5300)
if [ "$FRONTEND_HTTP" = "200" ]; then
    echo "   ✅ Frontend responding: HTTP $FRONTEND_HTTP"
else
    echo "   ❌ Frontend issue: HTTP $FRONTEND_HTTP"
fi
echo ""

# 3. Environment Check
echo "🔹 Frontend Environment:"
if [ -f /media/pts/Website/PromptTech_Solution_Site/frontend/.env ]; then
    echo "   Backend URL: $(grep REACT_APP_BACKEND_URL /media/pts/Website/PromptTech_Solution_Site/frontend/.env)"
else
    echo "   ❌ No .env file"
fi
echo ""

# 4. CORS Test
echo "🔹 CORS Headers:"
curl -s -I -H "Origin: http://localhost:5300" http://localhost:8181/api/services 2>/dev/null | grep -i "access-control-allow" | head -2
echo ""

# 5. PM2 Status
echo "🔹 PM2 Process Status:"
pm2 list | grep techzone
echo ""

# 6. Test actual frontend API call
echo "🔹 Simulating Frontend API Call:"
API_TEST=$(node -e "
const axios = require('axios');
axios.get('http://localhost:8181/api/services')
  .then(res => {
    console.log(\`   ✅ Axios call successful: \${res.data.length} services\`);
    console.log(\`   First service: \${res.data[0].name}\`);
  })
  .catch(err => {
    console.log(\`   ❌ Axios error: \${err.message}\`);
  });
" 2>&1)
echo "$API_TEST"
echo ""

# 7. Check if React is rendering
echo "🔹 React Bundle Check:"
if curl -s http://localhost:5300 | grep -q "root"; then
    echo "   ✅ React root div present"
else
    echo "   ❌ React root div missing"
fi

if curl -s http://localhost:5300 | grep -q "static/js/bundle.js"; then
    echo "   ✅ JS bundle included"
else
    echo "   ❌ JS bundle missing"
fi
echo ""

# 8. Browser Cache Warning
echo "╔════════════════════════════════════════════════════════╗"
echo "║              IMPORTANT - Browser Cache                ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "If services still don't show in browser, you MUST:"
echo "   1. Open browser DevTools (F12)"
echo "   2. Right-click the reload button"
echo "   3. Select 'Empty Cache and Hard Reload'"
echo "   OR"
echo "   4. Press: Ctrl+Shift+Delete"
echo "   5. Clear 'Cached images and files'"
echo "   6. Reload page with: Ctrl+Shift+R"
echo ""
echo "Browser caching is very aggressive and will serve old"
echo "JavaScript even though the server has new code!"
echo ""

# Summary
echo "╔════════════════════════════════════════════════════════╗"
echo "║                    Summary                             ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

if [ "$BACKEND_COUNT" != "ERROR" ] && [ "$BACKEND_COUNT" -gt 0 ]; then
    echo "✅ Backend API: Working ($BACKEND_COUNT services)"
else
    echo "❌ Backend API: Not working"
fi

if [ "$FRONTEND_HTTP" = "200" ]; then
    echo "✅ Frontend Server: Running"
else
    echo "❌ Frontend Server: Not responding"
fi

echo ""
echo "🌐 Access URLs:"
echo "   Frontend: http://localhost:5300/services"
echo "   Backend:  http://localhost:8181/api/services"
echo ""
