#!/usr/bin/env bash
# Start, attach, kill, detach, or list tmux agent sessions
#
# Usage:
#   ./start-agent.sh              # attach/create session 1 (default)
#   ./start-agent.sh 1|2|3        # attach/create session by number
#   ./start-agent.sh kill [1|2|3] # kill a session
#   ./start-agent.sh detach [1|2|3] # detach all clients from a session
#   ./start-agent.sh list         # list all tmux sessions

WORKDIR="/workspace"

# ---- Helper: map number to session name ----
session_name() {
    case "${1:-1}" in
        1) echo "agent" ;;
        2) echo "agent2" ;;
        3) echo "agent3" ;;
        *) return 1 ;;
    esac
}

# ---- Parse arguments ----
ACTION="start"
SESSION_NUM="1"

case "$1" in
    kill|detach|list)
        ACTION="$1"
        SESSION_NUM="${2:-1}"
        ;;
    1|2|3|"")
        ACTION="start"
        SESSION_NUM="${1:-1}"
        ;;
    *)
        echo "Usage: $0 [1|2|3|kill|detach|list] [1|2|3]"
        exit 1
        ;;
esac

# ---- Handle 'list' early (no session needed) ----
if [ "$ACTION" = "list" ]; then
    tmux ls 2>/dev/null || echo "No tmux sessions running."
    exit 0
fi

# ---- Resolve session name ----
SESSION_NAME=$(session_name "$SESSION_NUM")
if [ -z "$SESSION_NAME" ]; then
    echo "Invalid session number: $SESSION_NUM (use 1, 2, or 3)"
    exit 1
fi

# ---- Handle kill ----
if [ "$ACTION" = "kill" ]; then
    if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
        tmux kill-session -t "$SESSION_NAME"
        echo "Killed session: $SESSION_NAME"
    else
        echo "Session not found: $SESSION_NAME"
    fi
    exit 0
fi

# ---- Handle detach ----
if [ "$ACTION" = "detach" ]; then
    if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
        tmux detach-client -s "$SESSION_NAME"
        echo "Detached all clients from: $SESSION_NAME"
    else
        echo "Session not found: $SESSION_NAME"
    fi
    exit 0
fi

# ---- NVM bootstrap (available, not forced) ----
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

NVM_LOAD='
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
'

# ---- Clean stale socket if tmux server is dead ----
TMUX_SOCK="/tmp/tmux-$(id -u)/default"
if [ -e "$TMUX_SOCK" ] && ! tmux ls &>/dev/null; then
    rm -f "$TMUX_SOCK"
fi

# ---- Attach if exists ----
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
    echo "Attaching to existing session: $SESSION_NAME"
    tmux attach-session -t "$SESSION_NAME"
    exit 0
fi

echo "Creating new session: $SESSION_NAME"

# ---- Create session ----
tmux new-session -d -s "$SESSION_NAME" -c "$WORKDIR"

# ---- Enable mouse (click between panes + scroll) ----
tmux set-option -g mouse on

# Pane 2: Right
tmux split-window -h -t "$SESSION_NAME:1" -c "$WORKDIR"

# ---- Focus left pane & attach ----
tmux select-pane -t "$SESSION_NAME:1.1"
tmux attach-session -t "$SESSION_NAME"
