#!/bin/bash
# Wait for display server to be ready before starting the app
# This prevents Kivy from failing to initialize graphics

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MAX_WAIT=60
ELAPSED=0

echo "[$(date)] Waiting for display server to be ready..."

# Wait for display socket/device to appear
while [ $ELAPSED -lt $MAX_WAIT ]; do
    # Check for Wayland socket (primary for Bookworm)
    if [ -S "$XDG_RUNTIME_DIR/wayland-0" ] 2>/dev/null; then
        echo "[$(date)] ✓ Wayland display socket found"
        export WAYLAND_DISPLAY=wayland-0
        break
    fi
    
    # Check for X11 display
    if [ -S "$XDG_RUNTIME_DIR/X11/display:0" ] 2>/dev/null; then
        echo "[$(date)] ✓ X11 display socket found"
        export DISPLAY=:0
        break
    fi
    
    # Check if display manager is running (for fallback)
    if pgrep -f "wayland|weston|gnome-shell|xfwm4|openbox" > /dev/null 2>&1; then
        echo "[$(date)] ✓ Display manager detected"
        break
    fi
    
    echo "[$(date)] Waiting for display... ($ELAPSED/$MAX_WAIT seconds)"
    sleep 1
    ((ELAPSED++))
done

if [ $ELAPSED -ge $MAX_WAIT ]; then
    echo "[$(date)] ⚠️  Display timeout after $MAX_WAIT seconds, proceeding anyway..."
fi

# Set default display if not detected
if [ -z "$WAYLAND_DISPLAY" ] && [ -z "$DISPLAY" ]; then
    echo "[$(date)] Using fallback display settings"
    export DISPLAY=:0
    export WAYLAND_DISPLAY=wayland-0
fi

echo "[$(date)] Environment: DISPLAY=$DISPLAY WAYLAND_DISPLAY=$WAYLAND_DISPLAY"
echo "[$(date)] XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR"

# Now start the app
cd "$SCRIPT_DIR" || exit 1
exec bash start.sh
