#!/usr/bin/env bash
# claude-sessions — list and reattach the protected sessions started by _human-session.
#
#   claude-sessions            attach the most recently started detached session
#   claude-sessions list       one line per session
#   claude-sessions <name>     attach that session
set -uo pipefail

SOCK="$HOME/.local/state/human-session/tmux.sock"
FMT='#{session_name}\t#{?session_attached,attached,detached}\t#{@human_runtime}\t#{@human_started}\t#{@human_cwd}'

tmux_() { tmux -S "$SOCK" "$@"; }

if ! tmux_ list-sessions >/dev/null 2>&1; then
  printf 'claude-sessions: no protected sessions are running\n' >&2
  exit 1
fi

case "${1:-attach}" in
  list|-l|--list)
    printf 'NAME\tSTATE\tRUNTIME\tSTARTED\tCWD\n'
    tmux_ list-sessions -F "$FMT"
    ;;
  attach)
    target="$(tmux_ list-sessions -F '#{session_created} #{session_attached} #{session_name}' |
      awk '$2 == 0' | sort -rn | head -1 | cut -d' ' -f3-)"
    if [[ -z "$target" ]]; then
      printf 'claude-sessions: every session is already attached elsewhere:\n' >&2
      tmux_ list-sessions -F "$FMT" >&2
      exit 1
    fi
    exec tmux -S "$SOCK" attach-session -t "$target"
    ;;
  *)
    exec tmux -S "$SOCK" attach-session -t "$1"
    ;;
esac
