#!/bin/bash

if [[ $# -eq 1 ]]; then
    selected="$1"
else
    selected=$(project-finder ~/repos/ ~/Nextcloud/ ~/Obsidian/ | sk --height 16)
fi

if [[ -z "$selected" ]]; then
    exit 0
fi

selected_name=$(basename "$selected" | tr . _)

# Check if the session exists
if ! tmux has-session -t="$selected_name" 2>/dev/null; then
    # Create a new session, detached, with window 0 in the selected directory
    tmux new-session -d -s "$selected_name" -c "$selected"
    # Create a second window (index 1) in the same directory
    tmux new-window -t "$selected_name:" -c "$selected"
fi

# Always select window 0
tmux select-window -t "$selected_name:1"

if [[ -z "$TMUX" ]]; then
    # Not inside tmux, attach to the session
    tmux attach-session -t "$selected_name"
else
    # Inside tmux, switch client to the session
    tmux switch-client -t "$selected_name"
fi
