#!/bin/bash

# Player Status Checker
# Check if the player is running and healthy

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HEARTBEAT_FILE="$SCRIPT_DIR/.player_heartbeat"
STOP_FLAG_FILE="$SCRIPT_DIR/.player_stop_requested"
LOG_FILE="$SCRIPT_DIR/player_watchdog.log"

echo "=========================================="
echo "Kivy Signage Player - Status Check"
echo "=========================================="
echo ""

# Check for stop flag
if [ -f "$STOP_FLAG_FILE" ]; then
    echo "🛑 Stop Flag: PRESENT (user requested exit)"
    echo "   Watchdog will not restart player"
    echo "   To restart: ./start.sh"
    echo ""
fi

# Check if player process is running
PLAYER_PID=$(pgrep -f "python3 main.py" | head -1)

if [ -z "$PLAYER_PID" ]; then
    echo "Status: ❌ NOT RUNNING"
    echo ""
    echo "Player process is not running"
else
    echo "Status: ✓ RUNNING"
    echo "PID: $PLAYER_PID"
    echo ""
    
    # Check heartbeat
    if [ -f "$HEARTBEAT_FILE" ]; then
        last_update=$(stat -c %Y "$HEARTBEAT_FILE" 2>/dev/null || echo 0)
        current_time=$(date +%s)
        diff=$((current_time - last_update))
        
        echo "Heartbeat: $(date -d @${last_update} '+%Y-%m-%d %H:%M:%S')"
        echo "Last update: ${diff}s ago"
        
        if [ $diff -lt 60 ]; then
            echo "Health: ✓ HEALTHY"
        else
            echo "Health: ⚠️  STALE (may be frozen)"
        fi
    else
        echo "Heartbeat: Not found (player may be starting)"
    fi
fi

echo ""

# Show watchdog status
if pgrep -f "start.sh" > /dev/null; then
    echo "Watchdog: ✓ ACTIVE"
else
    echo "Watchdog: ❌ NOT RUNNING"
    echo ""
    echo "To start with watchdog: ./start.sh"
fi

echo ""

# Show last few log entries
if [ -f "$LOG_FILE" ]; then
    echo "=========================================="
    echo "Recent Log Entries (last 10):"
    echo "=========================================="
    tail -10 "$LOG_FILE"
fi

echo ""
