#!/bin/bash
# Complete Services Verification - Database to Frontend

echo "╔════════════════════════════════════════════════════════╗"
echo "║    Complete Services Flow Verification                ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

# 1. Database Check
echo "🔹 Step 1: Database Check"
cd /media/pts/Website/PromptTech_Solution_Site/backend
source venv/bin/activate
python3 << 'EOF'
import asyncio
from database import AsyncSessionLocal
from sqlalchemy import select, func
from models import Service

async def check():
    async with AsyncSessionLocal() as session:
        result = await session.execute(
            select(func.count(Service.id)).where(Service.is_active == True)
        )
        count = result.scalar()
        print(f"   ✅ Database has {count} active services")

asyncio.run(check())
EOF
echo ""

# 2. Backend API Check
echo "🔹 Step 2: Backend API Check"
API_RESPONSE=$(curl -s 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")
if [ "$API_COUNT" = "ERROR" ]; then
    echo "   ❌ Backend API error"
else
    echo "   ✅ Backend API returns $API_COUNT services"
fi
echo ""

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

# 4. PM2 Status
echo "🔹 Step 4: PM2 Process Status"
pm2 list | grep techzone | awk '{print "   " $2 ": " $10}'
echo ""

# 5. Test URLs
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Test URLs - Open in Browser              ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "1. Debug Page (shows API fetch in real-time):"
echo "   http://localhost:5300/debug-services"
echo ""
echo "2. Main Services Page:"
echo "   http://localhost:5300/services"
echo ""
echo "3. Backend API Direct:"
echo "   http://localhost:8181/api/services"
echo ""
echo "4. Test HTML Page:"
echo "   http://localhost:8888/test_api.html"
echo ""

# 6. Sample Data
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Sample Services Data                      ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "$API_RESPONSE" | python3 -c '
import sys, json
try:
    services = json.load(sys.stdin)
    for i, s in enumerate(services[:4], 1):
        print(f"   {i}. {s[\"name\"]} ({s[\"category\"]}) - ${s[\"price\"]}")
except:
    print("   Could not parse services")
'
echo "   ... and more"
echo ""

# 7. Browser Cache Warning
echo "╔════════════════════════════════════════════════════════╗"
echo "║          IMPORTANT: Clear Browser Cache!              ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "If services don't show, you MUST clear browser cache:"
echo "   • Press: Ctrl+Shift+R (hard refresh)"
echo "   • Or: Open DevTools (F12) → Network tab → Disable cache"
echo "   • Or: Try incognito/private window"
echo ""
echo "The backend is working! It's a browser caching issue."
echo ""
