# License: GPL-3.0-or-later
# (c) 2024 Dridi Boukelmoune <dridi.boukelmoune@gmail.com>

_tsess_usage() {
	tsess -qh "$@" 2>/dev/null
}

_tsess_arg_word() {
	w=$1
	w=$((w + 1))
	shift
	while test $w -lt "${#COMP_WORDS[@]}"
	do
		word=${COMP_WORDS[w]}
		case $word in
		--)
			echo $((w + 1))
			return
			;;
		-*)
			kind=$(
				_tsess_usage "$@" |
				awk -v opt="$word" '$2 == opt {print $1}'
			)
			if test "$kind" = param
			then
				w=$((w + 1))
			fi
			;;
		*)
			if test $w -ne "$cword"
			then
				echo $w
				return
			fi
			;;
		esac
		w=$((w + 1))
	done
	echo 0
}

_tsess() {
	_get_comp_words_by_ref prev cur cword
	cmdword=$(_tsess_arg_word 0)
	cmdname=${COMP_WORDS[cmdword]}
	argword=$(_tsess_arg_word "$cmdword" "$cmdname")
	tsesswords=$(_tsess_usage | awk '{print $2}')
	tsesscmds=$(_tsess_usage | awk '$1 == "cmd" {print $2}')
	tsessopts=$(_tsess_usage | awk '$1 == "opt" {print $2}')

	genwords=
	genarg=
	if test "$cmdword" -eq 0
	then
		genwords=$tsesswords
	elif test "$cword" -eq "$cmdword"
	then
		genwords=$tsesscmds
	elif test "$cword" -lt "$cmdword"
	then
		genwords=$tsessopts
	elif test "$cur" != "${cur#-}"
	then
		genwords=$(_tsess_usage "$cmdname" | awk '{print $2}')
	elif test "$prev" != "${prev#-}"
	then
		# XXX: does not support options with args before subcommand
		genarg=$(
			_tsess_usage "$cmdname" |
			awk -v "opt=$prev" \
				'$1 == "param" && $2 == opt {print $3}'
		)
	elif test "$argword" = 0
	then
		# XXX: does not support subcommand with multiple args
		genwords=$(
			_tsess_usage "$cmdname" |
			awk '$1 != "arg" {print $2}'
		)
		genarg=$(
			_tsess_usage "$cmdname" |
			awk '$1 == "arg" {print $2; exit}'
		)
	fi

	case $genarg in
	name)
		genargs=$(tsess -q list 2>/dev/null)
		genwords="$genwords $genargs"
		;;
	socket-name)
		tmuxdir=${TMUX_TMPDIR:-/tmp}
		genwords=$(
			find "$tmuxdir"/tmux-*/* -maxdepth 0 -type s \
				2>/dev/null |
			xargs -n1 basename
		)
		;;
	socket-path|file)
		COMPREPLY=($(compgen -f -- "$cur"))
		return
		;;
	'')
		;;
	esac

	COMPREPLY=($(compgen -W "$genwords" -- "$cur"))
}

complete -F _tsess tsess
