#!/bin/bash

set -euo pipefail

SESSION_NAME="xn0"
# This PATH line is a little hacky, used to ensure my
#   ~/bin/kitty script is used to set the background colors
PATH=${HOME}/bin:${PATH}

# Cleanup function to kill unattached xn0g# sessions
cleanup_sessions() {
    echo "Looking for unattached xn0g# sessions to cleanup..."

    # Get all sessions that match xn0g# pattern
    local sessions_to_kill=()

    # List all sessions and filter for xn0g# pattern with 0 attached clients
    while IFS=' ' read -r session_name attached_count; do
        sessions_to_kill+=("$session_name")
    done < <(tmux list-sessions -F "#{session_name} #{session_attached}" 2>/dev/null | awk '$1 ~ /^xn0g[0-9]+$/ && $2 == 0 {print $1, $2}' || true)

    if [[ ${#sessions_to_kill[@]} -eq 0 ]]; then
        echo "No unattached xn0g# sessions found."
        return
    fi

    echo "Found ${#sessions_to_kill[@]} unattached session(s) to cleanup:"
    for session in "${sessions_to_kill[@]}"; do
        echo "  - $session"
    done

    for session in "${sessions_to_kill[@]}"; do
        echo "Killing session: $session"
        tmux kill-session -t "$session"
    done

    echo "Cleanup completed."
}

# Handle cleanup argument
if [[ "${1:-}" == "cleanup" ]]; then
    cleanup_sessions
    exit 0
fi

# Function to find next available session name or unattached session
find_session() {
    for ((counter=1; ; counter++)); do
        local session_name="xn0g$counter"

        if tmux has-session -t "$session_name" 2>/dev/null; then
            # Check if this session has no attached clients
            local attached_clients=$(tmux list-sessions -F "#{session_name} #{session_attached}" | awk -v name="$session_name" '$1 == name {print $2}')
            if [[ "$attached_clients" -eq 0 ]]; then
                echo "$session_name"
                return
            fi
        else
            # Session doesn't exist, we can create it
            echo "$session_name"
            return
        fi
    done
}

# Check if tmux session exists and has attached clients
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
    # Get number of attached clients to the session
    attached_clients=$(tmux list-sessions -F "#{session_name} #{session_attached}" | awk -v name="$SESSION_NAME" '$1 == name {print $2}')

    if [[ "$attached_clients" -gt 0 ]]; then
        NEW_SESSION_NAME=$(find_session)

        # TODO this code path is very borken, I don't think the ELSE ever runs.
        if tmux has-session -t "$NEW_SESSION_NAME" 2>/dev/null; then
            echo "Session '$NEW_SESSION_NAME' exists and has attached clients. Attaching to existing session."
            exec kitty tmux attach-session -t "$NEW_SESSION_NAME" \; new-window -n ""
        else
            echo "Session '$SESSION_NAME' exists with $attached_clients attached client(s). Creating new session '$NEW_SESSION_NAME' targeting '$SESSION_NAME'."
            exec kitty tmux new-session -t "$SESSION_NAME" -s "$NEW_SESSION_NAME"
        fi
    else
        echo "Session '$SESSION_NAME' exists but has no attached clients. Attaching to existing session."
        exec kitty tmux attach-session -t "$SESSION_NAME"
    fi
else
    echo "Session '$SESSION_NAME' does not exist. Creating new session."
    exec kitty tmux new-session -s "$SESSION_NAME" -n ""
fi
