#!/bin/zsh
source ~/.zshrc
echo "🚀 Initiating Safe Relaunch Protocol for Theme Cannon..."

PID=$(pgrep -x "Theme Cannon")
if [ -z "$PID" ]; then
    echo "   -> Theme Cannon is not running. Proceeding directly to launch."
else
    echo "   -> Theme Cannon is running (PID: ${PID}). Sending graceful quit command..."
    osascript -e 'tell application "Theme Cannon" to quit saving no'
    
    echo "   -> Waiting for process to terminate..."
    TIMEOUT=50
    COUNT=0
    while pgrep -x "Theme Cannon" > /dev/null; do
        sleep 0.1
        COUNT=$((COUNT + 1))
        if [ "$COUNT" -ge "$TIMEOUT" ]; then
            echo "   -> 🛑 ERROR: Timeout reached. Theme Cannon failed to quit." >&2
            exit 1
        fi
    done
    echo "   -> Process terminated."
fi

echo "🚀 Setting Scheme and Clicking Run..."
osascript -e '
tell application "Xcode"
    activate
    open POSIX file "/Users/dave/warezfactory/xcode/Factory_Apps/Theme Cannon/Theme Cannon.xcodeproj/"
    try
        tell workspace document "Theme Cannon.xcodeproj"
            set active scheme to scheme "Theme Cannon"
        end tell
    end try
end tell
delay 0.5
tell application "System Events"
    tell process "Xcode"
        click menu item "Run" of menu "Product" of menu bar 1
    end tell
end tell
'
echo "✅ Safe Relaunch command sent to Xcode."