#!/bin/bash
# Usage: ~/open-iterm-tab <session-name>
# Opens a tmux session in iTerm2 - reuses existing tab if found, otherwise opens new
# Sets both the profile name (for detection) and tab title (for visual display)

SESSION="$1"
if [ -z "$SESSION" ]; then
    echo "Usage: ~/open-iterm-tab <session-name>"
    exit 1
fi

# Verify tmux session exists
if ! tmux has-session -t "$SESSION" 2>/dev/null; then
    echo "Error: tmux session '$SESSION' does not exist"
    exit 1
fi

# Check if there's already an iTerm2 tab with this session's profile name
result=$(osascript -e "
tell application \"iTerm2\"
    activate
    repeat with aWindow in windows
        repeat with aTab in tabs of aWindow
            repeat with aSession in sessions of aTab
                try
                    if profile name of aSession is equal to \"$SESSION\" then
                        select aWindow
                        select aTab
                        return \"EXISTING\"
                    end if
                end try
            end repeat
        end repeat
    end repeat
    return \"NOT_FOUND\"
end tell
" 2>&1)

if [ "$result" = "EXISTING" ]; then
    echo "✓ Switched to existing tab for $SESSION"
else
    echo "Opening new tab for $SESSION..."
    osascript -e "
    tell application \"iTerm2\"
        activate
        tell current window
            create tab with default profile
            tell current session
                -- Set profile name for programmatic detection
                set name to \"$SESSION\"
                -- Set visible tab title via escape code, then attach to tmux
                write text \"printf '\\\\033]0;$SESSION\\\\007' && tmux attach -t $SESSION\"
            end tell
        end tell
    end tell
    " 2>&1
    echo "✓ Opened $SESSION in new iTerm2 tab"
fi
