#!/bin/bash
# ================================================
# Math Platform - Complete System Verification
# ================================================

set -e

# 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

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

echo -e "${CYAN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║   Math Platform - Complete System Verification           ║${NC}"
echo -e "${CYAN}║   $(date '+%Y-%m-%d %H:%M:%S')                                  ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════╝${NC}"

total_checks=0
passed_checks=0
failed_checks=0
warned_checks=0

# Function to perform check
check() {
    local description=$1
    local command=$2
    local severity=${3:-ERROR}  # ERROR or WARN

    total_checks=$((total_checks + 1))
    echo -n "[$total_checks] $description... "

    if eval "$command" > /dev/null 2>&1; then
        echo -e "${GREEN}PASS${NC}"
        passed_checks=$((passed_checks + 1))
        return 0
    else
        if [ "$severity" = "WARN" ]; then
            echo -e "${YELLOW}WARN${NC}"
            warned_checks=$((warned_checks + 1))
        else
            echo -e "${RED}FAIL${NC}"
            failed_checks=$((failed_checks + 1))
        fi
        return 1
    fi
}

# Section 1: Docker Environment
echo -e "\n${BLUE}═══ Docker Environment ═══${NC}"
check "Docker daemon running" "docker info"
check "Docker Compose available" "command -v docker-compose || docker compose version"

# Section 2: Configuration Files
echo -e "\n${BLUE}═══ Configuration Files ═══${NC}"
check "docker-compose.yml exists" "test -f $PROJECT_ROOT/docker-compose.yml"
check ".env file exists" "test -f $PROJECT_ROOT/.env"
check "Backend Dockerfile exists" "test -f $PROJECT_ROOT/docker/Dockerfile.backend"
check "Frontend Dockerfile exists" "test -f $PROJECT_ROOT/docker/Dockerfile.frontend"
check "Worker Dockerfile exists" "test -f $PROJECT_ROOT/docker/Dockerfile.worker"
check "Nginx config exists" "test -f $PROJECT_ROOT/docker/nginx.conf"

# Section 3: Application Structure
echo -e "\n${BLUE}═══ Application Structure ═══${NC}"
check "Backend package.json exists" "test -f $PROJECT_ROOT/backend/package.json"
check "Frontend package.json exists" "test -f $PROJECT_ROOT/frontend/package.json"
check "Prisma schema exists" "test -f $PROJECT_ROOT/backend/prisma/schema.prisma"
check "Next.js config exists" "test -f $PROJECT_ROOT/frontend/next.config.js"
check "Backend src directory exists" "test -d $PROJECT_ROOT/backend/src"
check "Frontend src directory exists" "test -d $PROJECT_ROOT/frontend/src"

# Section 4: Scripts
echo -e "\n${BLUE}═══ Management Scripts ═══${NC}"
check "start.sh is executable" "test -x $PROJECT_ROOT/docker/start.sh"
check "stop.sh is executable" "test -x $PROJECT_ROOT/docker/stop.sh"
check "backup.sh is executable" "test -x $PROJECT_ROOT/docker/backup.sh"
check "test-e2e.sh is executable" "test -x $PROJECT_ROOT/scripts/test-e2e.sh"
check "health-check.sh is executable" "test -x $PROJECT_ROOT/scripts/health-check.sh"
check "validate-deployment.sh is executable" "test -x $PROJECT_ROOT/scripts/validate-deployment.sh"

# Section 5: Directories
echo -e "\n${BLUE}═══ Required Directories ═══${NC}"
check "docker/data directory exists" "test -d $PROJECT_ROOT/docker/data"
check "docker/logs directory exists" "test -d $PROJECT_ROOT/docker/logs"
check "docker/init-scripts directory exists" "test -d $PROJECT_ROOT/docker/init-scripts"
check "pdfs directory exists" "test -d $PROJECT_ROOT/pdfs"
check "scripts directory exists" "test -d $PROJECT_ROOT/scripts"

# Section 6: Environment Variables (if services are running)
echo -e "\n${BLUE}═══ Environment Variables ═══${NC}"

if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"

    check "DB_PASSWORD is set" "test -n '$DB_PASSWORD'" "WARN"
    check "REDIS_PASSWORD is set" "test -n '$REDIS_PASSWORD'" "WARN"
    check "JWT_SECRET is set" "test -n '$JWT_SECRET'" "WARN"
    check "AI_API_KEY is set" "test -n '$AI_API_KEY'" "WARN"
else
    echo -e "${YELLOW}.env file not found, skipping variable checks${NC}"
fi

# Section 7: Services (if running)
echo -e "\n${BLUE}═══ Running Services ═══${NC}"

if docker info > /dev/null 2>&1; then
    check "PostgreSQL container running" "docker ps | grep -q math-postgres" "WARN"
    check "Redis container running" "docker ps | grep -q math-redis" "WARN"
    check "Backend container running" "docker ps | grep -q math-backend" "WARN"
    check "Frontend container running" "docker ps | grep -q math-frontend" "WARN"
    check "Nginx container running" "docker ps | grep -q math-nginx" "WARN"
else
    echo -e "${YELLOW}Docker not running, skipping service checks${NC}"
fi

# Section 8: Service Health (if running)
echo -e "\n${BLUE}═══ Service Health Endpoints ═══${NC}"

if curl -s http://localhost:3001/health > /dev/null 2>&1; then
    check "Backend API health endpoint" "curl -s -f http://localhost:3001/health" "WARN"
else
    echo -e "${YELLOW}Backend not accessible, skipping health checks${NC}"
fi

if curl -s http://localhost:3000 > /dev/null 2>&1; then
    check "Frontend web server" "curl -s -f http://localhost:3000" "WARN"
else
    echo -e "${YELLOW}Frontend not accessible, skipping health checks${NC}"
fi

# Section 9: Port Availability (if services not running)
echo -e "\n${BLUE}═══ Port Availability ═══${NC}"

if ! docker ps | grep -q math-postgres; then
    check "Port 5432 available" "! netstat -tuln 2>/dev/null | grep -q ':5432 ' || ! ss -tuln 2>/dev/null | grep -q ':5432 '" "WARN"
else
    echo -e "${YELLOW}PostgreSQL running, skipping port check${NC}"
fi

if ! docker ps | grep -q math-redis; then
    check "Port 6379 available" "! netstat -tuln 2>/dev/null | grep -q ':6379 ' || ! ss -tuln 2>/dev/null | grep -q ':6379 '" "WARN"
else
    echo -e "${YELLOW}Redis running, skipping port check${NC}"
fi

# Section 10: System Resources
echo -e "\n${BLUE}═══ System Resources ═══${NC}"

DISK_USAGE=$(df -h "$PROJECT_ROOT" | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -lt 80 ]; then
    check "Disk space OK (using ${DISK_USAGE}%)" "true"
else
    check "Disk space low (using ${DISK_USAGE}%)" "false" "WARN"
fi

MEM_USAGE=$(free | awk 'NR==2{printf "%.0f", $3*100/$2}')
if [ "$MEM_USAGE" -lt 90 ]; then
    check "Memory OK (using ${MEM_USAGE}%)" "true"
else
    check "Memory high (using ${MEM_USAGE}%)" "false" "WARN"
fi

# Final Summary
echo -e "\n${CYAN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║                    Verification Summary                      ║${NC}"
echo -e "${CYAN}╠════════════════════════════════════════════════════════════╣${NC}"
printf "${CYAN}║  Total Checks:  %-3d                                           ║${NC}\n" $total_checks
printf "${GREEN}║  Passed:       %-3d                                           ║${NC}\n" $passed_checks
printf "${RED}║  Failed:       %-3d                                           ║${NC}\n" $failed_checks
printf "${YELLOW}║  Warnings:     %-3d                                           ║${NC}\n" $warned_checks
echo -e "${CYAN}╚════════════════════════════════════════════════════════════╝${NC}"

if [ $failed_checks -eq 0 ]; then
    echo -e "\n${GREEN}✓ All critical checks passed!${NC}\n"

    if [ $warned_checks -gt 0 ]; then
        echo -e "${YELLOW}⚠ Some warnings detected. Review above for details.${NC}\n"
    fi

    echo -e "${BLUE}Next steps:${NC}"
    echo -e "  1. Start services: ${CYAN}./docker/start.sh${NC}"
    echo -e "  2. Run health check: ${CYAN}./scripts/health-check.sh${NC}"
    echo -e "  3. Run E2E tests: ${CYAN}./scripts/test-e2e.sh${NC}"
    echo -e "  4. View documentation: ${CYAN}cat DEPLOY.md${NC}\n"

    exit 0
else
    echo -e "\n${RED}✗ Some critical checks failed!${NC}"
    echo -e "${RED}  Please resolve the issues above before proceeding.${NC}\n"
    exit 1
fi
