#!/bin/bash

# Queue Monitor - Real-time Queue Status Monitor
# Displays live queue statistics and failed jobs

set -e

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
GRAY='\033[0;37m'
NC='\033[0m'

# Change to project root
cd "$(dirname "$0")/.."

# Load database helper functions
source "$(dirname "$0")/_db-helper.sh"

# Check MySQL connection
if ! db_test_connection; then
    echo -e "${RED}Error: Cannot connect to MySQL database${NC}"
    exit 1
fi

# Function to count jobs
count_jobs() {
    db_count_where "jobs" "queue='$1'" 2>/dev/null || echo "0"
}

# Function to count failed jobs
count_failed() {
    db_count "failed_jobs" 2>/dev/null || echo "0"
}

# Function to get queue worker status
worker_status() {
    if pgrep -f "queue:work" > /dev/null; then
        echo -e "${GREEN}RUNNING${NC}"
        return 0
    else
        echo -e "${RED}STOPPED${NC}"
        return 1
    fi
}

# Main monitoring loop
clear
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Queue Monitor (Press Ctrl+C to exit)${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# One-time display or continuous monitoring
MODE="${1:-watch}"

while true; do
    # Clear screen for watch mode
    if [ "$MODE" = "watch" ]; then
        tput cup 4 0  # Move cursor to line 4
        tput ed       # Clear to end of screen
    fi

    # Queue Worker Status
    echo -e "${YELLOW}Queue Worker:${NC} $(worker_status)"
    echo ""

    # Queue Statistics
    CRITICAL_JOBS=$(count_jobs "critical")
    TICKETS_JOBS=$(count_jobs "tickets")
    DEFAULT_JOBS=$(count_jobs "default")
    BULK_JOBS=$(count_jobs "bulk")
    TOTAL_JOBS=$((CRITICAL_JOBS + TICKETS_JOBS + DEFAULT_JOBS + BULK_JOBS))
    FAILED_JOBS=$(count_failed)

    echo -e "${YELLOW}Queue Statistics:${NC}"
    echo -e "  ${BLUE}Critical Queue:${NC}  $CRITICAL_JOBS jobs"
    echo -e "  ${BLUE}Tickets Queue:${NC}   $TICKETS_JOBS jobs"
    echo -e "  ${BLUE}Default Queue:${NC}   $DEFAULT_JOBS jobs"
    echo -e "  ${BLUE}Bulk Queue:${NC}      $BULK_JOBS jobs"
    echo -e "  ${GRAY}────────────────────────${NC}"
    echo -e "  ${GREEN}Total Pending:${NC}   $TOTAL_JOBS jobs"
    echo ""

    # Failed Jobs
    if [ "$FAILED_JOBS" -gt 0 ]; then
        echo -e "${RED}Failed Jobs:${NC}     $FAILED_JOBS jobs"
        echo -e "${YELLOW}  Run: php artisan queue:retry all${NC}"
    else
        echo -e "${GREEN}Failed Jobs:${NC}     0 jobs"
    fi
    echo ""

    # Recent Jobs (last 5)
    echo -e "${YELLOW}Recent Jobs (last 5):${NC}"
    RECENT_JOBS=$(db_query "
        SELECT CONCAT('  ', queue, ' | ', SUBSTRING(payload, 1, 50), '...')
        FROM jobs
        ORDER BY created_at DESC
        LIMIT 5
    " 2>/dev/null || echo "  No jobs in queue")

    if [ -z "$RECENT_JOBS" ]; then
        echo -e "${GRAY}  No jobs in queue${NC}"
    else
        echo -e "${GRAY}$RECENT_JOBS${NC}"
    fi
    echo ""

    # Queue Worker Processes
    echo -e "${YELLOW}Queue Worker Processes:${NC}"
    WORKER_PROCESSES=$(ps aux | grep "queue:work" | grep -v grep | wc -l | tr -d ' ')
    if [ "$WORKER_PROCESSES" -gt 0 ]; then
        ps aux | grep "queue:work" | grep -v grep | awk '{print "  PID "$2" | "$11" "$12" "$13" "$14" "$15}' || echo "  None"
    else
        echo -e "  ${RED}No workers running${NC}"
        echo -e "  ${YELLOW}Start with: ./scripts/start-queue-worker.sh${NC}"
    fi
    echo ""

    # Actions
    echo -e "${GRAY}────────────────────────────────────────${NC}"
    echo -e "${YELLOW}Quick Actions:${NC}"
    echo -e "  ${BLUE}Start worker:${NC}    ./scripts/start-queue-worker.sh"
    echo -e "  ${BLUE}Retry failed:${NC}    php artisan queue:retry all"
    echo -e "  ${BLUE}Clear queue:${NC}     php artisan queue:flush"
    echo -e "  ${BLUE}View failed:${NC}     php artisan queue:failed"

    # Exit if one-time mode
    if [ "$MODE" != "watch" ]; then
        break
    fi

    # Wait before refreshing
    sleep 2
done
