#!/bin/bash
# Check status of backend and frontend services
# Shows running state, health, ports, and version info

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$SCRIPT_DIR/logs"
BACKEND_PORT=8000
FRONTEND_PORT=3000

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

# Parse arguments
WATCH_MODE=false
JSON_OUTPUT=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --watch|-w)
            WATCH_MODE=true
            shift
            ;;
        --json|-j)
            JSON_OUTPUT=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --watch, -w   Continuously monitor (refresh every 2s)"
            echo "  --json, -j    Output in JSON format"
            echo "  --help, -h    Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Function to check if a port is in use and get the PID
check_port() {
    local port=$1
    lsof -ti :"$port" 2>/dev/null | head -1
}

# Function to check HTTP health
check_health() {
    local url=$1
    local timeout=${2:-2}
    if curl -s --max-time "$timeout" "$url" > /dev/null 2>&1; then
        echo "healthy"
    else
        echo "unhealthy"
    fi
}

# Function to get process uptime
get_uptime() {
    local pid=$1
    if [ -n "$pid" ] && ps -p "$pid" > /dev/null 2>&1; then
        ps -p "$pid" -o etime= 2>/dev/null | xargs
    else
        echo "N/A"
    fi
}

# Function to get memory usage
get_memory() {
    local pid=$1
    if [ -n "$pid" ] && ps -p "$pid" > /dev/null 2>&1; then
        ps -p "$pid" -o rss= 2>/dev/null | awk '{printf "%.1f MB", $1/1024}'
    else
        echo "N/A"
    fi
}

# Main status check function
check_status() {
    # Get PIDs from files
    BACKEND_PID_FILE=""
    FRONTEND_PID_FILE=""

    if [ -f "$LOG_DIR/backend.pid" ]; then
        BACKEND_PID_FILE=$(cat "$LOG_DIR/backend.pid")
    fi

    if [ -f "$LOG_DIR/frontend.pid" ]; then
        FRONTEND_PID_FILE=$(cat "$LOG_DIR/frontend.pid")
    fi

    # Check actual running processes
    BACKEND_PID_PORT=$(check_port $BACKEND_PORT)
    FRONTEND_PID_PORT=$(check_port $FRONTEND_PORT)

    # Determine backend status
    BACKEND_RUNNING=false
    BACKEND_PID=""
    if [ -n "$BACKEND_PID_FILE" ] && ps -p "$BACKEND_PID_FILE" > /dev/null 2>&1; then
        BACKEND_RUNNING=true
        BACKEND_PID="$BACKEND_PID_FILE"
    elif [ -n "$BACKEND_PID_PORT" ]; then
        BACKEND_RUNNING=true
        BACKEND_PID="$BACKEND_PID_PORT"
    fi

    # Determine frontend status
    FRONTEND_RUNNING=false
    FRONTEND_PID=""
    if [ -n "$FRONTEND_PID_FILE" ] && ps -p "$FRONTEND_PID_FILE" > /dev/null 2>&1; then
        FRONTEND_RUNNING=true
        FRONTEND_PID="$FRONTEND_PID_FILE"
    elif [ -n "$FRONTEND_PID_PORT" ]; then
        FRONTEND_RUNNING=true
        FRONTEND_PID="$FRONTEND_PID_PORT"
    fi

    # Check health
    BACKEND_HEALTH="stopped"
    FRONTEND_HEALTH="stopped"

    if [ "$BACKEND_RUNNING" = true ]; then
        BACKEND_HEALTH=$(check_health "http://localhost:$BACKEND_PORT/health")
        if [ "$BACKEND_HEALTH" = "unhealthy" ]; then
            # Try root endpoint as fallback
            BACKEND_HEALTH=$(check_health "http://localhost:$BACKEND_PORT/")
        fi
    fi

    if [ "$FRONTEND_RUNNING" = true ]; then
        FRONTEND_HEALTH=$(check_health "http://localhost:$FRONTEND_PORT")
    fi

    # Get version info from startup log
    GIT_COMMIT="unknown"
    GIT_BRANCH="unknown"
    START_TIME="unknown"
    ENV_MODE="unknown"

    if [ -f "$LOG_DIR/startup.log" ]; then
        GIT_COMMIT=$(grep "Git Commit:" "$LOG_DIR/startup.log" 2>/dev/null | cut -d: -f2 | xargs || echo "unknown")
        GIT_BRANCH=$(grep "Git Branch:" "$LOG_DIR/startup.log" 2>/dev/null | cut -d: -f2 | xargs || echo "unknown")
        START_TIME=$(grep "Timestamp:" "$LOG_DIR/startup.log" 2>/dev/null | cut -d: -f2- | xargs || echo "unknown")
        ENV_MODE=$(grep "Environment:" "$LOG_DIR/startup.log" 2>/dev/null | cut -d: -f2 | xargs || echo "unknown")
    fi

    if [ "$JSON_OUTPUT" = true ]; then
        # JSON output
        cat << EOF
{
  "backend": {
    "running": $BACKEND_RUNNING,
    "pid": ${BACKEND_PID:-null},
    "port": $BACKEND_PORT,
    "health": "$BACKEND_HEALTH",
    "uptime": "$(get_uptime "$BACKEND_PID")",
    "memory": "$(get_memory "$BACKEND_PID")"
  },
  "frontend": {
    "running": $FRONTEND_RUNNING,
    "pid": ${FRONTEND_PID:-null},
    "port": $FRONTEND_PORT,
    "health": "$FRONTEND_HEALTH",
    "uptime": "$(get_uptime "$FRONTEND_PID")",
    "memory": "$(get_memory "$FRONTEND_PID")"
  },
  "version": {
    "branch": "$GIT_BRANCH",
    "commit": "$GIT_COMMIT",
    "mode": "$ENV_MODE",
    "started": "$START_TIME"
  }
}
EOF
    else
        # Human-readable output
        clear 2>/dev/null || true

        echo "========================================"
        echo "📊 SBA Gameplay Services Status"
        echo "========================================"
        echo ""

        # Backend status
        echo -n "📡 Backend:  "
        if [ "$BACKEND_RUNNING" = true ]; then
            if [ "$BACKEND_HEALTH" = "healthy" ]; then
                echo -e "${GREEN}● Running${NC} (healthy)"
            else
                echo -e "${YELLOW}● Running${NC} (unhealthy)"
            fi
            echo "   PID:     $BACKEND_PID"
            echo "   Port:    $BACKEND_PORT"
            echo "   Uptime:  $(get_uptime "$BACKEND_PID")"
            echo "   Memory:  $(get_memory "$BACKEND_PID")"
            echo "   URL:     http://localhost:$BACKEND_PORT"
        else
            echo -e "${RED}○ Stopped${NC}"
        fi
        echo ""

        # Frontend status
        echo -n "🎨 Frontend: "
        if [ "$FRONTEND_RUNNING" = true ]; then
            if [ "$FRONTEND_HEALTH" = "healthy" ]; then
                echo -e "${GREEN}● Running${NC} (healthy)"
            else
                echo -e "${YELLOW}● Running${NC} (unhealthy)"
            fi
            echo "   PID:     $FRONTEND_PID"
            echo "   Port:    $FRONTEND_PORT"
            echo "   Uptime:  $(get_uptime "$FRONTEND_PID")"
            echo "   Memory:  $(get_memory "$FRONTEND_PID")"
            echo "   URL:     http://localhost:$FRONTEND_PORT"
        else
            echo -e "${RED}○ Stopped${NC}"
        fi
        echo ""

        # Version info
        echo "📌 Version:"
        echo "   Branch:  $GIT_BRANCH"
        echo "   Commit:  $GIT_COMMIT"
        echo "   Mode:    $ENV_MODE"
        echo "   Started: $START_TIME"
        echo ""

        # Overall status
        if [ "$BACKEND_RUNNING" = true ] && [ "$FRONTEND_RUNNING" = true ]; then
            if [ "$BACKEND_HEALTH" = "healthy" ] && [ "$FRONTEND_HEALTH" = "healthy" ]; then
                echo -e "${GREEN}✅ All services healthy${NC}"
            else
                echo -e "${YELLOW}⚠️  Some services unhealthy${NC}"
            fi
        elif [ "$BACKEND_RUNNING" = true ] || [ "$FRONTEND_RUNNING" = true ]; then
            echo -e "${YELLOW}⚠️  Partial services running${NC}"
        else
            echo -e "${RED}❌ All services stopped${NC}"
        fi
        echo ""

        # Quick commands
        echo "📋 Commands:"
        if [ "$BACKEND_RUNNING" = false ] || [ "$FRONTEND_RUNNING" = false ]; then
            echo "   Start:   ./start-services.sh"
        fi
        if [ "$BACKEND_RUNNING" = true ] || [ "$FRONTEND_RUNNING" = true ]; then
            echo "   Stop:    ./stop-services.sh"
            echo "   Restart: ./stop-services.sh && ./start-services.sh"
        fi
        echo "   Logs:    tail -f $LOG_DIR/backend.log"
        echo ""

        if [ "$WATCH_MODE" = true ]; then
            echo -e "${BLUE}[Refreshing every 2s - Press Ctrl+C to exit]${NC}"
        fi
    fi
}

# Main execution
if [ "$WATCH_MODE" = true ]; then
    # Watch mode - refresh every 2 seconds
    while true; do
        check_status
        sleep 2
    done
else
    check_status
fi
