#!/bin/bash

# GNX-WEB Deployment Verification Script
# Checks if all components are properly configured and running

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

echo -e "${BLUE}=========================================="
echo "GNX-WEB Deployment Verification"
echo "==========================================${NC}"
echo ""

ERRORS=0
WARNINGS=0

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to check if port is listening
port_listening() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1 || netstat -tlnp 2>/dev/null | grep -q ":$port " || ss -tlnp 2>/dev/null | grep -q ":$port "; then
        return 0
    else
        return 1
    fi
}

# Check required commands
echo -e "${BLUE}Checking required commands...${NC}"
for cmd in python3 node npm nginx psql; do
    if command_exists $cmd; then
        echo -e "${GREEN}✓${NC} $cmd is installed"
    else
        echo -e "${RED}✗${NC} $cmd is NOT installed"
        ((ERRORS++))
    fi
done

# Check PM2
if command_exists pm2; then
    echo -e "${GREEN}✓${NC} PM2 is installed"
else
    echo -e "${YELLOW}⚠${NC} PM2 is not installed (recommended for process management)"
    ((WARNINGS++))
fi

echo ""

# Check backend
echo -e "${BLUE}Checking Backend...${NC}"
if [ -f "backEnd/.env" ]; then
    echo -e "${GREEN}✓${NC} Backend .env file exists"
    
    # Check for critical variables
    if grep -q "SECRET_KEY=" backEnd/.env && ! grep -q "your-super-secret" backEnd/.env; then
        echo -e "${GREEN}✓${NC} SECRET_KEY is set"
    else
        echo -e "${RED}✗${NC} SECRET_KEY not properly configured"
        ((ERRORS++))
    fi
    
    if grep -q "INTERNAL_API_KEY=" backEnd/.env && ! grep -q "PLACEHOLDER\|your-secure-api-key" backEnd/.env; then
        echo -e "${GREEN}✓${NC} INTERNAL_API_KEY is set"
    else
        echo -e "${RED}✗${NC} INTERNAL_API_KEY not properly configured"
        ((ERRORS++))
    fi
    
    if grep -q "DATABASE_URL=" backEnd/.env && ! grep -q "your_password_here" backEnd/.env; then
        echo -e "${GREEN}✓${NC} DATABASE_URL is configured"
    else
        echo -e "${YELLOW}⚠${NC} DATABASE_URL may not be configured"
        ((WARNINGS++))
    fi
else
    echo -e "${RED}✗${NC} Backend .env file not found"
    ((ERRORS++))
fi

if [ -d "backEnd/venv" ]; then
    echo -e "${GREEN}✓${NC} Backend virtual environment exists"
else
    echo -e "${YELLOW}⚠${NC} Backend virtual environment not found"
    ((WARNINGS++))
fi

if port_listening 1086; then
    echo -e "${GREEN}✓${NC} Backend is running on port 1086"
else
    echo -e "${YELLOW}⚠${NC} Backend is not running on port 1086"
    ((WARNINGS++))
fi

echo ""

# Check frontend
echo -e "${BLUE}Checking Frontend...${NC}"
if [ -f "frontEnd/.env.production" ]; then
    echo -e "${GREEN}✓${NC} Frontend .env.production exists"
else
    echo -e "${YELLOW}⚠${NC} Frontend .env.production not found"
    ((WARNINGS++))
fi

if [ -d "frontEnd/node_modules" ]; then
    echo -e "${GREEN}✓${NC} Frontend node_modules exists"
else
    echo -e "${YELLOW}⚠${NC} Frontend node_modules not found (run npm install)"
    ((WARNINGS++))
fi

if [ -d "frontEnd/.next" ]; then
    echo -e "${GREEN}✓${NC} Frontend build exists"
else
    echo -e "${YELLOW}⚠${NC} Frontend not built (run npm run build)"
    ((WARNINGS++))
fi

if port_listening 1087; then
    echo -e "${GREEN}✓${NC} Frontend is running on port 1087"
else
    echo -e "${YELLOW}⚠${NC} Frontend is not running on port 1087"
    ((WARNINGS++))
fi

echo ""

# Check database
echo -e "${BLUE}Checking Database...${NC}"
if port_listening 5433; then
    echo -e "${GREEN}✓${NC} PostgreSQL is running on port 5433"
else
    echo -e "${YELLOW}⚠${NC} PostgreSQL is not running on port 5433"
    ((WARNINGS++))
fi

if command_exists psql; then
    DB_URL=$(grep "^DATABASE_URL=" backEnd/.env 2>/dev/null | cut -d'=' -f2-)
    if [ -n "$DB_URL" ] && [[ "$DB_URL" == postgresql://* ]]; then
        # Extract components from postgresql://user:password@host:port/database
        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
            if PGPASSWORD="$DB_PASS" psql -h "${DB_HOST:-localhost}" -p "${DB_PORT:-5433}" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" >/dev/null 2>&1; then
                echo -e "${GREEN}✓${NC} Database connection successful"
            else
                echo -e "${YELLOW}⚠${NC} Could not verify database connection (check credentials)"
                ((WARNINGS++))
            fi
        else
            echo -e "${YELLOW}⚠${NC} Could not parse DATABASE_URL for connection test"
            ((WARNINGS++))
        fi
    else
        echo -e "${YELLOW}⚠${NC} DATABASE_URL not found or invalid format"
        ((WARNINGS++))
    fi
fi

echo ""

# Check nginx
echo -e "${BLUE}Checking Nginx...${NC}"
if [ -f "/etc/nginx/sites-available/gnxsoft" ]; then
    echo -e "${GREEN}✓${NC} Nginx configuration exists"
    
    if [ -L "/etc/nginx/sites-enabled/gnxsoft" ]; then
        echo -e "${GREEN}✓${NC} Nginx site is enabled"
    else
        echo -e "${YELLOW}⚠${NC} Nginx site is not enabled"
        ((WARNINGS++))
    fi
    
    if grep -q "PLACEHOLDER_INTERNAL_API_KEY" /etc/nginx/sites-available/gnxsoft; then
        echo -e "${RED}✗${NC} Nginx config still has PLACEHOLDER_INTERNAL_API_KEY"
        ((ERRORS++))
    else
        echo -e "${GREEN}✓${NC} Nginx INTERNAL_API_KEY is configured"
    fi
else
    echo -e "${YELLOW}⚠${NC} Nginx configuration not found"
    ((WARNINGS++))
fi

if systemctl is-active --quiet nginx 2>/dev/null; then
    echo -e "${GREEN}✓${NC} Nginx is running"
else
    echo -e "${YELLOW}⚠${NC} Nginx is not running"
    ((WARNINGS++))
fi

if port_listening 80; then
    echo -e "${GREEN}✓${NC} HTTP port 80 is listening"
else
    echo -e "${YELLOW}⚠${NC} HTTP port 80 is not listening"
    ((WARNINGS++))
fi

if port_listening 443; then
    echo -e "${GREEN}✓${NC} HTTPS port 443 is listening"
else
    echo -e "${YELLOW}⚠${NC} HTTPS port 443 is not listening"
    ((WARNINGS++))
fi

echo ""

# Check firewall
echo -e "${BLUE}Checking Firewall...${NC}"
if command_exists ufw; then
    if ufw status | grep -q "Status: active"; then
        echo -e "${GREEN}✓${NC} UFW firewall is active"
    else
        echo -e "${YELLOW}⚠${NC} UFW firewall is not active"
        ((WARNINGS++))
    fi
else
    echo -e "${YELLOW}⚠${NC} UFW not found (firewall may be managed differently)"
    ((WARNINGS++))
fi

echo ""

# Check PM2 services
if command_exists pm2; then
    echo -e "${BLUE}Checking PM2 Services...${NC}"
    if pm2 list | grep -q "gnxsoft-backend"; then
        if pm2 list | grep -q "gnxsoft-backend.*online"; then
            echo -e "${GREEN}✓${NC} Backend service is running in PM2"
        else
            echo -e "${YELLOW}⚠${NC} Backend service exists but may not be online"
            ((WARNINGS++))
        fi
    else
        echo -e "${YELLOW}⚠${NC} Backend service not found in PM2"
        ((WARNINGS++))
    fi
    
    if pm2 list | grep -q "gnxsoft-frontend"; then
        if pm2 list | grep -q "gnxsoft-frontend.*online"; then
            echo -e "${GREEN}✓${NC} Frontend service is running in PM2"
        else
            echo -e "${YELLOW}⚠${NC} Frontend service exists but may not be online"
            ((WARNINGS++))
        fi
    else
        echo -e "${YELLOW}⚠${NC} Frontend service not found in PM2"
        ((WARNINGS++))
    fi
fi

echo ""
echo -e "${BLUE}=========================================="
echo "Verification Summary"
echo "==========================================${NC}"

if [ $ERRORS -eq 0 ] && [ $WARNINGS -eq 0 ]; then
    echo -e "${GREEN}✓ All checks passed!${NC}"
    exit 0
elif [ $ERRORS -eq 0 ]; then
    echo -e "${YELLOW}⚠ $WARNINGS warning(s) found${NC}"
    echo -e "${GREEN}✓ No critical errors${NC}"
    exit 0
else
    echo -e "${RED}✗ $ERRORS error(s) found${NC}"
    if [ $WARNINGS -gt 0 ]; then
        echo -e "${YELLOW}⚠ $WARNINGS warning(s) found${NC}"
    fi
    exit 1
fi

