#!/bin/bash
# ================================================
# Math Platform - Monitoring Script
# ================================================

# 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

clear

while true; do
    clear
    echo -e "${CYAN}╔═══════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║     Math Platform - Real-time Monitor                ║${NC}"
    echo -e "${CYAN}║     $(date '+%Y-%m-%d %H:%M:%S')                    ║${NC}"
    echo -e "${CYAN}╚═══════════════════════════════════════════════════════╝${NC}"

    # System Resources
    echo -e "\n${BLUE}System Resources${NC}"
    echo "----------------------------------------"
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
    MEM_USAGE=$(free | awk 'NR==2{printf "%.1f%%", $3*100/$2}')
    DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}')

    echo -e "CPU:    ${CPU_USAGE}%"
    echo -e "Memory: ${MEM_USAGE}"
    echo -e "Disk:   ${DISK_USAGE}"

    # Docker Containers
    echo -e "\n${BLUE}Container Status${NC}"
    echo "----------------------------------------"

    containers=("math-postgres" "math-redis" "math-backend" "math-frontend" "math-nginx" "math-pdf-worker" "math-exercise-worker" "math-notification-worker")

    for container in "${containers[@]}"; do
        if docker ps | grep -q "$container"; then
            status=$(docker inspect --format='{{.State.Status}}' "$container" 2>/dev/null)
            health=$(docker inspect --format='{{.State.Health.Status}}' "$container" 2>/dev/null || echo "no-check")

            if [ "$health" = "healthy" ] || [ "$health" = "no-check" ]; then
                echo -e "${GREEN}✓${NC} $container (${status})"
            else
                echo -e "${YELLOW}⚠${NC} $container (${health})"
            fi
        else
            echo -e "${RED}✗${NC} $container (not running)"
        fi
    done

    # Resource Usage per Container
    echo -e "\n${BLUE}Container Resource Usage${NC}"
    echo "----------------------------------------"
    echo -e "Container\tCPU\tMemory\tNet I/O"
    echo -e "---------\t---\t------\t-------"

    docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}" 2>/dev/null | grep math- | head -7

    # Service Health
    echo -e "\n${BLUE}Service Health${NC}"
    echo "----------------------------------------"

    # Backend
    if curl -s http://localhost:3001/health > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} Backend API (http://localhost:3001)"
    else
        echo -e "${RED}✗${NC} Backend API (http://localhost:3001)"
    fi

    # Frontend
    if curl -s http://localhost:3000 > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} Frontend (http://localhost:3000)"
    else
        echo -e "${RED}✗${NC} Frontend (http://localhost:3000)"
    fi

    # Nginx
    if curl -s http://localhost:80 > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} Nginx (http://localhost:80)"
    else
        echo -e "${RED}✗${NC} Nginx (http://localhost:80)"
    fi

    # Recent Logs (last 5 lines)
    echo -e "\n${BLUE}Recent Backend Logs${NC}"
    echo "----------------------------------------"
    docker logs --tail=5 math-backend 2>&1 | grep -v "^$" || echo "No logs available"

    # Database Stats
    echo -e "\n${BLUE}Database Stats${NC}"
    echo "----------------------------------------"
    DB_SIZE=$(docker exec math-postgres psql -U mathuser -d mathdb -t -c "SELECT pg_size_pretty(pg_database_size('mathdb'));" 2>/dev/null | xargs || echo "N/A")
    DB_CONNS=$(docker exec math-postgres psql -U mathuser -d mathdb -t -c "SELECT count(*) FROM pg_stat_activity;" 2>/dev/null | xargs || echo "N/A")
    echo -e "Database Size: ${DB_SIZE}"
    echo -e "Active Connections: ${DB_CONNS}"

    # Queue Stats
    echo -e "\n${BLUE}Queue Stats (Redis)${NC}"
    echo "----------------------------------------"
    QUEUE_INFO=$(docker exec math-redis redis-cli -a "${REDIS_PASSWORD:-redis_secure_password_2024}" INFO stats 2>/dev/null | grep -E "total_connections_received|total_commands_processed" | cut -d: -f2 | xargs || echo "N/A")
    echo -e "Connections: $(echo "$QUEUE_INFO" | head -1)"
    echo -e "Commands: $(echo "$QUEUE_INFO" | tail -1)"

    # Instructions
    echo -e "\n${YELLOW}Press Ctrl+C to exit${NC}"
    echo -e "${YELLOW}Refreshing in 5 seconds...${NC}"

    sleep 5
done
