#!/bin/bash

# SKG UCP Debug Script
# This script helps identify why the application is crashing

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}     SKG UCP Debug Information${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

# Check Node.js
echo -e "${YELLOW}[1] Node.js Version:${NC}"
node -v 2>/dev/null || echo -e "${RED}Node.js not found!${NC}"
echo ""

# Check if .env exists
echo -e "${YELLOW}[2] Environment File:${NC}"
if [ -f ".env" ]; then
    echo -e "${GREEN}.env file exists${NC}"
    echo "Contents (passwords hidden):"
    cat .env | sed 's/PASSWORD=.*/PASSWORD=***HIDDEN***/' | sed 's/SECRET=.*/SECRET=***HIDDEN***/'
else
    echo -e "${RED}.env file NOT FOUND!${NC}"
fi
echo ""

# Check if node_modules exists
echo -e "${YELLOW}[3] Dependencies:${NC}"
if [ -d "node_modules" ]; then
    echo -e "${GREEN}node_modules exists${NC}"
else
    echo -e "${RED}node_modules NOT FOUND! Run: pnpm install${NC}"
fi
echo ""

# Check if .next exists
echo -e "${YELLOW}[4] Build Output:${NC}"
if [ -d ".next" ]; then
    echo -e "${GREEN}.next build folder exists${NC}"
else
    echo -e "${RED}.next NOT FOUND! Run: pnpm build${NC}"
fi
echo ""

# Check if prisma client is generated
echo -e "${YELLOW}[5] Prisma Client:${NC}"
if [ -d "node_modules/.prisma/client" ]; then
    echo -e "${GREEN}Prisma client generated${NC}"
else
    echo -e "${RED}Prisma client NOT generated! Run: pnpm db:generate${NC}"
fi
echo ""

# Test database connection
echo -e "${YELLOW}[6] Database Connection Test:${NC}"
if [ -f ".env" ]; then
    DB_URL=$(grep DATABASE_URL .env | cut -d'"' -f2)
    if [ -n "$DB_URL" ]; then
        # Extract connection details
        DB_HOST=$(echo $DB_URL | sed -n 's/.*@\([^:\/]*\).*/\1/p')
        DB_PORT=$(echo $DB_URL | sed -n 's/.*:\([0-9]*\)\/.*/\1/p')
        
        echo "Testing connection to $DB_HOST:$DB_PORT..."
        if command -v mysql &> /dev/null; then
            timeout 5 bash -c "echo > /dev/tcp/$DB_HOST/$DB_PORT" 2>/dev/null
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}Database port is reachable${NC}"
            else
                echo -e "${RED}Cannot connect to database!${NC}"
            fi
        else
            echo "mysql client not installed, skipping connection test"
        fi
    fi
fi
echo ""

# PM2 Status
echo -e "${YELLOW}[7] PM2 Status:${NC}"
pm2 status 2>/dev/null || echo "PM2 not running"
echo ""

# PM2 Logs
echo -e "${YELLOW}[8] Recent PM2 Error Logs:${NC}"
echo -e "${RED}----------------------------------------${NC}"
pm2 logs skg-ucp --lines 50 --nostream 2>/dev/null | tail -100
echo -e "${RED}----------------------------------------${NC}"
echo ""

# Try to start manually and capture error
echo -e "${YELLOW}[9] Manual Start Test:${NC}"
echo "Stopping PM2 process..."
pm2 stop skg-ucp 2>/dev/null

echo "Attempting manual start (will show error directly)..."
echo -e "${RED}----------------------------------------${NC}"
timeout 10 pnpm start 2>&1 || true
echo -e "${RED}----------------------------------------${NC}"

echo ""
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}Debug complete. Check the errors above.${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""
echo "Common fixes:"
echo "1. Missing .env: Run ./install.sh again"
echo "2. Database error: Check DATABASE_URL in .env"
echo "3. Build error: Run 'pnpm build'"
echo "4. Prisma error: Run 'pnpm db:generate && pnpm db:push'"
