#!/bin/bash
PLIST_PATH="$HOME/Library/LaunchAgents/com.crawfordifland.Sideline-Captions.Helper.plist"

# Get the app path from the script location (this script is in Contents/Resources/)
SCRIPT_DIR="$(dirname "$0")"
APP_BUNDLE="$(dirname "$(dirname "$SCRIPT_DIR")")"
APP_PATH="$APP_BUNDLE"

# Log startup for debugging
echo "$(date): SidelineCaptionsHelper.sh started" >> /tmp/sideline-launcher.log

# Track previous state of Photo Mechanic (0 = not running, 1 = running)
PM_WAS_RUNNING=0

while true; do
    # First check: If the plist file doesn't exist, the setting was disabled - exit immediately
    if [ ! -f "$PLIST_PATH" ]; then
        echo "$(date): Plist not found, exiting" >> /tmp/sideline-launcher.log
        exit 0
    fi
    
    # Check if Photo Mechanic is currently running
    PM_IS_RUNNING=0
    if pgrep -f "Photo Mechanic" > /dev/null || pgrep -f "PhotoMechanic" > /dev/null; then
        PM_IS_RUNNING=1
    fi
    
    # Only launch Sideline when PM transitions from NOT running to running
    # This means PM just opened, so we should launch Sideline once
    if [ $PM_IS_RUNNING -eq 1 ] && [ $PM_WAS_RUNNING -eq 0 ]; then
        # PM just launched - verify plist still exists (setting still enabled)
        if [ -f "$PLIST_PATH" ]; then
            # Check if Sideline Captions is NOT running
            if ! pgrep -f "Sideline Captions" > /dev/null; then
                echo "$(date): Photo Mechanic just launched, launching Sideline Captions" >> /tmp/sideline-launcher.log
                # Launch Sideline Captions
                open -a "$APP_PATH"
            fi
        else
            # Setting was disabled, exit
            echo "$(date): Plist removed while running, exiting" >> /tmp/sideline-launcher.log
            exit 0
        fi
    fi
    
    # Update previous state for next iteration
    PM_WAS_RUNNING=$PM_IS_RUNNING
    
    # Sleep between checks (shorter interval for faster detection)
    sleep 1
done

