#!/bin/bash
# Complete Services Page Diagnostic

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

# 1. Check Backend API
echo "🔹 Backend API Status:"
SERVICES_API=$(curl -s http://localhost:8181/api/services)
SERVICES_COUNT=$(echo "$SERVICES_API" | python3 -c 'import sys,json; print(len(json.load(sys.stdin)))' 2>/dev/null || echo "ERROR")
if [ "$SERVICES_COUNT" = "ERROR" ]; then
    echo "   ❌ Backend API returned error or invalid JSON"
    echo "   Response: $SERVICES_API"
else
    echo "   ✅ Backend API working: $SERVICES_COUNT services"
    echo ""
    echo "   Services returned:"
    echo "$SERVICES_API" | python3 -c 'import sys,json; [print(f"     • {s[\"name\"]} ({s[\"category\"]})") for s in json.load(sys.stdin)]' 2>/dev/null
fi
echo ""

# 2. Check Frontend Process
echo "🔹 Frontend Process:"
FRONTEND_PID=$(ps aux | grep -E "node.*5300|@craco/craco.*start" | grep -v grep | awk '{print $2}' | head -1)
if [ -z "$FRONTEND_PID" ]; then
    echo "   ❌ Frontend NOT running"
else
    echo "   ✅ Frontend running (PID: $FRONTEND_PID)"
    echo "   Process: $(ps aux | grep $FRONTEND_PID | grep -v grep | head -1 | awk '{for(i=11;i<=NF;i++) printf $i" "; print ""}')"
fi
echo ""

# 3. Check Frontend HTTP
echo "🔹 Frontend HTTP 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 ""

# 4. Check Environment Variables
echo "🔹 Frontend Environment (.env):"
if [ -f /media/pts/Website/PromptTech_Solution_Site/frontend/.env ]; then
    cat /media/pts/Website/PromptTech_Solution_Site/frontend/.env | grep -E "REACT_APP|PORT" | while read line; do
        echo "   $line"
    done
else
    echo "   ❌ No .env file found"
fi
echo ""

# 5. Test API from Frontend Context
echo "🔹 Testing API Call (simulating frontend):"
API_RESPONSE=$(curl -s -H "Origin: http://localhost:5300" http://localhost:8181/api/services)
API_COUNT=$(echo "$API_RESPONSE" | python3 -c 'import sys,json; print(len(json.load(sys.stdin)))' 2>/dev/null || echo "ERROR")
echo "   Services received: $API_COUNT"
echo ""

# 6. Check CORS Headers
echo "🔹 CORS Headers Check:"
curl -s -I -H "Origin: http://localhost:5300" http://localhost:8181/api/services | grep -i "access-control" | while read line; do
    echo "   $line"
done
echo ""

# 7. Check Services.js file
echo "🔹 Frontend Services.js Configuration:"
echo "   API URL: $(grep 'const API' /media/pts/Website/PromptTech_Solution_Site/frontend/src/pages/Services.js | head -1)"
echo "   Using cache: $(grep -q 'getCached' /media/pts/Website/PromptTech_Solution_Site/frontend/src/pages/Services.js && echo 'YES' || echo 'NO')"
echo ""

# 8. Check for JavaScript errors (if build logs exist)
echo "🔹 Recent Frontend Build Status:"
if [ -f /media/pts/Website/PromptTech_Solution_Site/frontend/npm-debug.log ]; then
    echo "   ⚠️  npm-debug.log exists - there may be errors"
    tail -5 /media/pts/Website/PromptTech_Solution_Site/frontend/npm-debug.log
else
    echo "   ✅ No npm-debug.log found"
fi
echo ""

# 9. Test actual page load
echo "🔹 Testing Services Page Load:"
PAGE_CONTENT=$(curl -s http://localhost:5300/services 2>&1)
if echo "$PAGE_CONTENT" | grep -q "<!DOCTYPE html>"; then
    echo "   ✅ Services page loads HTML"
    if echo "$PAGE_CONTENT" | grep -q "root"; then
        echo "   ✅ React root div present"
    else
        echo "   ⚠️  React root div not found"
    fi
else
    echo "   ❌ Services page returned: $(echo "$PAGE_CONTENT" | head -3)"
fi
echo ""

# 10. Check backend logs for recent /services requests
echo "🔹 Recent Backend Activity:"
if [ -f /media/pts/Website/PromptTech_Solution_Site/backend/server.log ]; then
    echo "   Last 3 /services requests:"
    grep "GET /api/services" /media/pts/Website/PromptTech_Solution_Site/backend/server.log | tail -3
else
    echo "   No server.log found"
fi
echo ""

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

# Summary
if [ "$SERVICES_COUNT" != "ERROR" ] && [ "$SERVICES_COUNT" -gt 0 ]; then
    echo "✅ Backend: $SERVICES_COUNT services available"
else
    echo "❌ Backend: Services API not working"
fi

if [ ! -z "$FRONTEND_PID" ] && [ "$FRONTEND_HTTP" = "200" ]; then
    echo "✅ Frontend: Running and responding"
else
    echo "❌ Frontend: Not running properly"
fi

echo ""
echo "🔍 If services still not loading in browser:"
echo "   1. Open browser DevTools (F12)"
echo "   2. Go to Console tab"
echo "   3. Navigate to http://localhost:5300/services"
echo "   4. Look for red errors related to API calls"
echo "   5. Check Network tab for failed requests"
echo ""
