#!/bin/bash

# GNX-WEB Services Slug Page Debugging Script
# Checks why /services/[slug] pages are not opening in production

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${BLUE}=========================================="
echo "Services Slug Page Debugging"
echo "==========================================${NC}"
echo ""

# Configuration
BACKEND_PORT=1086
FRONTEND_PORT=1087
API_BASE_URL="https://gnxsoft.com/api"
BACKEND_DIR="/var/www/GNX-WEB/backEnd"
FRONTEND_DIR="/var/www/GNX-WEB/frontEnd"

# Function to print section header
print_section() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo -e "$1"
    echo -e "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
}

# Function to test API endpoint
test_api() {
    local endpoint=$1
    local description=$2
    
    echo -e "${BLUE}Testing:${NC} $description"
    echo -e "${YELLOW}URL:${NC} $API_BASE_URL$endpoint"
    
    response=$(curl -s -w "\n%{http_code}" -H "X-Internal-API-Key: 9hZtPwyScigoBAl59Uvcz_9VztSRC6Zt_6L1B2xTM2M" "$API_BASE_URL$endpoint" 2>&1)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')
    
    if [ "$http_code" -eq 200 ]; then
        echo -e "${GREEN}✓ Status: $http_code (OK)${NC}"
        if [ -n "$body" ] && echo "$body" | grep -q "slug"; then
            echo -e "${GREEN}✓ Response contains service data${NC}"
            # Show first slug from response
            slug=$(echo "$body" | grep -o '"slug":"[^"]*"' | head -1 | cut -d'"' -f4)
            if [ -n "$slug" ]; then
                echo -e "${CYAN}Example slug found: $slug${NC}"
            fi
        fi
    else
        echo -e "${RED}✗ Status: $http_code (ERROR)${NC}"
        if [ -n "$body" ]; then
            echo -e "${YELLOW}Response:${NC}"
            echo "$body" | head -20
        fi
    fi
    echo ""
}

# 1. Check if services are running
print_section "1. SERVICE STATUS CHECK"

echo -e "${BLUE}Checking if services are running...${NC}"
if pm2 list | grep -q "gnxsoft-backend.*online"; then
    echo -e "${GREEN}✓ Backend is running in PM2${NC}"
else
    echo -e "${RED}✗ Backend is NOT running${NC}"
    echo -e "${YELLOW}Run: pm2 logs gnxsoft-backend${NC}"
fi

if pm2 list | grep -q "gnxsoft-frontend.*online"; then
    echo -e "${GREEN}✓ Frontend is running in PM2${NC}"
else
    echo -e "${RED}✗ Frontend is NOT running${NC}"
    echo -e "${YELLOW}Run: pm2 logs gnxsoft-frontend${NC}"
fi

# Check ports
if lsof -Pi :$BACKEND_PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${GREEN}✓ Backend port $BACKEND_PORT is listening${NC}"
else
    echo -e "${RED}✗ Backend port $BACKEND_PORT is NOT listening${NC}"
fi

if lsof -Pi :$FRONTEND_PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${GREEN}✓ Frontend port $FRONTEND_PORT is listening${NC}"
else
    echo -e "${RED}✗ Frontend port $FRONTEND_PORT is NOT listening${NC}"
fi

# 2. Check database for services
print_section "2. DATABASE CHECK"

if [ -f "$BACKEND_DIR/.env" ]; then
    DB_URL=$(grep "^DATABASE_URL=" "$BACKEND_DIR/.env" 2>/dev/null | cut -d'=' -f2-)
    if [ -n "$DB_URL" ] && [[ "$DB_URL" == postgresql://* ]]; then
        echo -e "${BLUE}Checking services in database...${NC}"
        
        # Extract database connection info
        DB_USER=$(echo "$DB_URL" | sed -n 's|.*://\([^:]*\):.*|\1|p')
        DB_PASS=$(echo "$DB_URL" | sed -n 's|.*://[^:]*:\([^@]*\)@.*|\1|p')
        DB_HOST=$(echo "$DB_URL" | sed -n 's|.*@\([^:]*\):.*|\1|p')
        DB_PORT=$(echo "$DB_URL" | sed -n 's|.*:\([0-9]*\)/.*|\1|p')
        DB_NAME=$(echo "$DB_URL" | sed -n 's|.*/\([^?]*\).*|\1|p')
        
        if [ -n "$DB_USER" ] && [ -n "$DB_PASS" ] && [ -n "$DB_NAME" ]; then
            # Count services
            service_count=$(PGPASSWORD="$DB_PASS" psql -h "${DB_HOST:-localhost}" -p "${DB_PORT:-5433}" -U "$DB_USER" -d "$DB_NAME" -t -c "SELECT COUNT(*) FROM services_service WHERE is_active = true;" 2>/dev/null | xargs)
            
            if [ -n "$service_count" ] && [ "$service_count" -gt 0 ]; then
                echo -e "${GREEN}✓ Found $service_count active service(s) in database${NC}"
                
                # Get list of slugs
                echo -e "${BLUE}Active service slugs:${NC}"
                PGPASSWORD="$DB_PASS" psql -h "${DB_HOST:-localhost}" -p "${DB_PORT:-5433}" -U "$DB_USER" -d "$DB_NAME" -t -c "SELECT slug FROM services_service WHERE is_active = true ORDER BY display_order;" 2>/dev/null | sed 's/^[ \t]*//' | while read slug; do
                    if [ -n "$slug" ]; then
                        echo -e "  ${CYAN}- $slug${NC}"
                    fi
                done
            else
                echo -e "${RED}✗ No active services found in database${NC}"
                echo -e "${YELLOW}Run: cd $BACKEND_DIR && source venv/bin/activate && python manage.py shell${NC}"
                echo -e "${YELLOW}Then check: from services.models import Service; Service.objects.filter(is_active=True).count()${NC}"
            fi
        else
            echo -e "${YELLOW}⚠ Could not parse database connection info${NC}"
        fi
    else
        echo -e "${YELLOW}⚠ DATABASE_URL not found or invalid${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Backend .env file not found${NC}"
fi

# 3. Test API endpoints
print_section "3. API ENDPOINT TESTS"

echo -e "${BLUE}Testing API endpoints (using internal proxy)...${NC}"
echo ""

# Test services list
test_api "/services/" "Services List Endpoint"

# Test a specific service (try first slug from database if available)
if [ -n "$DB_URL" ]; then
    first_slug=$(PGPASSWORD="$DB_PASS" psql -h "${DB_HOST:-localhost}" -p "${DB_PORT:-5433}" -U "$DB_USER" -d "$DB_NAME" -t -c "SELECT slug FROM services_service WHERE is_active = true ORDER BY display_order LIMIT 1;" 2>/dev/null | xargs)
    
    if [ -n "$first_slug" ]; then
        echo -e "${BLUE}Testing specific service slug:${NC} $first_slug"
        test_api "/services/$first_slug/" "Service Detail Endpoint (slug: $first_slug)"
    else
        echo -e "${YELLOW}⚠ No service slug found to test${NC}"
        echo -e "${YELLOW}Testing with a dummy slug to see error response...${NC}"
        test_api "/services/test-slug-123/" "Service Detail Endpoint (test - should return 404)"
    fi
fi

# 4. Check Next.js build and routing
print_section "4. NEXT.JS BUILD CHECK"

if [ -d "$FRONTEND_DIR/.next" ]; then
    echo -e "${GREEN}✓ Next.js build directory exists${NC}"
    
    # Check if routes are generated
    if [ -d "$FRONTEND_DIR/.next/server/app/services" ]; then
        echo -e "${GREEN}✓ Services routes directory exists${NC}"
        
        # Check for slug route
        if [ -d "$FRONTEND_DIR/.next/server/app/services/[slug]" ]; then
            echo -e "${GREEN}✓ Dynamic slug route exists${NC}"
        else
            echo -e "${RED}✗ Dynamic slug route NOT found${NC}"
            echo -e "${YELLOW}The route /services/[slug] may not be built${NC}"
        fi
    else
        echo -e "${RED}✗ Services routes directory NOT found${NC}"
    fi
else
    echo -e "${RED}✗ Next.js build directory NOT found${NC}"
    echo -e "${YELLOW}Run: cd $FRONTEND_DIR && npm run build${NC}"
fi

# Check if page file exists in source
if [ -f "$FRONTEND_DIR/app/services/[slug]/page.tsx" ]; then
    echo -e "${GREEN}✓ Source file exists: app/services/[slug]/page.tsx${NC}"
else
    echo -e "${RED}✗ Source file NOT found: app/services/[slug]/page.tsx${NC}"
fi

# 5. Check logs
print_section "5. LOG FILE CHECK"

echo -e "${BLUE}Checking recent errors in logs...${NC}"
echo ""

# Frontend logs (PM2)
echo -e "${CYAN}Frontend Logs (last 20 lines):${NC}"
pm2 logs gnxsoft-frontend --lines 20 --nostream 2>/dev/null | tail -20 || echo -e "${YELLOW}Could not read frontend logs${NC}"
echo ""

# Backend logs (PM2)
echo -e "${CYAN}Backend Logs (last 20 lines):${NC}"
pm2 logs gnxsoft-backend --lines 20 --nostream 2>/dev/null | tail -20 || echo -e "${YELLOW}Could not read backend logs${NC}"
echo ""

# Nginx error logs
if [ -f "/var/log/nginx/gnxsoft_error.log" ]; then
    echo -e "${CYAN}Nginx Error Logs (recent services-related):${NC}"
    grep -i "services" /var/log/nginx/gnxsoft_error.log | tail -10 || echo -e "${YELLOW}No service-related errors in nginx log${NC}"
    echo ""
fi

# Nginx access logs (check for 404s)
if [ -f "/var/log/nginx/gnxsoft_access.log" ]; then
    echo -e "${CYAN}Recent 404 errors for /services/*:${NC}"
    grep "GET /services/" /var/log/nginx/gnxsoft_access.log | grep " 404 " | tail -10 || echo -e "${YELLOW}No 404 errors for /services/* found${NC}"
    echo ""
fi

# 6. Test actual page access
print_section "6. PAGE ACCESS TEST"

if [ -n "$first_slug" ]; then
    test_url="https://gnxsoft.com/services/$first_slug"
    echo -e "${BLUE}Testing page access:${NC} $test_url"
    
    response=$(curl -s -w "\n%{http_code}" -L "$test_url" 2>&1)
    http_code=$(echo "$response" | tail -n1)
    
    if [ "$http_code" -eq 200 ]; then
        echo -e "${GREEN}✓ Page loads successfully (HTTP $http_code)${NC}"
        if echo "$response" | grep -qi "not found\|404\|error"; then
            echo -e "${YELLOW}⚠ Page loads but may contain error message${NC}"
        fi
    elif [ "$http_code" -eq 404 ]; then
        echo -e "${RED}✗ Page not found (HTTP 404)${NC}"
        echo -e "${YELLOW}Possible causes:${NC}"
        echo "  1. Service slug doesn't exist in database"
        echo "  2. Next.js route not generated"
        echo "  3. API call failing during page generation"
    elif [ "$http_code" -eq 500 ]; then
        echo -e "${RED}✗ Server error (HTTP 500)${NC}"
        echo -e "${YELLOW}Check server logs for details${NC}"
    else
        echo -e "${YELLOW}⚠ Unexpected status code: $http_code${NC}"
    fi
else
    echo -e "${YELLOW}⚠ No service slug available to test${NC}"
fi

# 7. Check API configuration
print_section "7. API CONFIGURATION CHECK"

if [ -f "$FRONTEND_DIR/lib/config/api.ts" ]; then
    echo -e "${BLUE}Checking API configuration...${NC}"
    
    # Check if using relative URLs in production
    if grep -q "BASE_URL.*=.*isProduction.*? ''" "$FRONTEND_DIR/lib/config/api.ts"; then
        echo -e "${GREEN}✓ API config uses relative URLs in production${NC}"
    else
        echo -e "${YELLOW}⚠ API config may not be using relative URLs${NC}"
    fi
    
    # Check .env.production
    if [ -f "$FRONTEND_DIR/.env.production" ]; then
        echo -e "${GREEN}✓ .env.production file exists${NC}"
        echo -e "${CYAN}Contents:${NC}"
        cat "$FRONTEND_DIR/.env.production" | grep -v "^#" | grep -v "^$"
    else
        echo -e "${YELLOW}⚠ .env.production file not found${NC}"
    fi
else
    echo -e "${RED}✗ API config file not found${NC}"
fi

# 8. Recommendations
print_section "8. RECOMMENDATIONS"

echo -e "${BLUE}Common fixes for services slug page issues:${NC}"
echo ""
echo -e "1. ${CYAN}If API is returning 404:${NC}"
echo "   - Check if service exists: cd $BACKEND_DIR && source venv/bin/activate"
echo "   - Run: python manage.py shell"
echo "   - Then: from services.models import Service; Service.objects.all()"
echo ""
echo -e "2. ${CYAN}If API is returning 500:${NC}"
echo "   - Check backend logs: pm2 logs gnxsoft-backend"
echo "   - Check Django logs: tail -f $BACKEND_DIR/logs/django.log"
echo ""
echo -e "3. ${CYAN}If page shows 404:${NC}"
echo "   - Rebuild frontend: cd $FRONTEND_DIR && npm run build"
echo "   - Restart frontend: pm2 restart gnxsoft-frontend"
echo ""
echo -e "4. ${CYAN}If API connection fails:${NC}"
echo "   - Test internal API: curl -H 'X-Internal-API-Key: YOUR_KEY' http://127.0.0.1:$BACKEND_PORT/api/services/"
echo "   - Check nginx config: sudo nginx -t"
echo "   - Check nginx logs: tail -f /var/log/nginx/gnxsoft_error.log"
echo ""
echo -e "5. ${CYAN}For real-time debugging:${NC}"
echo "   - Frontend logs: pm2 logs gnxsoft-frontend --lines 50"
echo "   - Backend logs: pm2 logs gnxsoft-backend --lines 50"
echo "   - Nginx access: tail -f /var/log/nginx/gnxsoft_access.log"
echo "   - Nginx errors: tail -f /var/log/nginx/gnxsoft_error.log"
echo ""

# 9. Quick test command
print_section "9. QUICK TEST COMMANDS"

echo -e "${BLUE}Copy and run these commands for detailed testing:${NC}"
echo ""
echo -e "${CYAN}# Test API directly (internal):${NC}"
echo "curl -H 'X-Internal-API-Key: 9hZtPwyScigoBAl59Uvcz_9VztSRC6Zt_6L1B2xTM2M' http://127.0.0.1:$BACKEND_PORT/api/services/"
echo ""
echo -e "${CYAN}# Test API through nginx (external):${NC}"
echo "curl -H 'X-Internal-API-Key: 9hZtPwyScigoBAl59Uvcz_9VztSRC6Zt_6L1B2xTM2M' https://gnxsoft.com/api/services/"
echo ""
echo -e "${CYAN}# Test a specific service (replace SLUG with actual slug):${NC}"
echo "curl -H 'X-Internal-API-Key: 9hZtPwyScigoBAl59Uvcz_9VztSRC6Zt_6L1B2xTM2M' https://gnxsoft.com/api/services/SLUG/"
echo ""
echo -e "${CYAN}# Check Next.js route in browser console:${NC}"
echo "Visit: https://gnxsoft.com/services/YOUR-SLUG"
echo "Open browser DevTools → Network tab → Check for failed API calls"
echo ""

echo -e "${GREEN}=========================================="
echo "Debugging complete!"
echo "==========================================${NC}"
echo ""

