# Bash completion for chroot-distro
#
# Install system-wide:
#   cp chroot-distro.bash /usr/share/bash-completion/completions/chroot-distro
# Install for current user:
#   mkdir -p ~/.local/share/bash-completion/completions
#   cp chroot-distro.bash ~/.local/share/bash-completion/completions/chroot-distro

_chroot_distro_get_containers() {
	local dir
	if _chroot_distro_is_termux; then
		dir="${TERMUX__PREFIX:-/data/data/com.termux/files/usr}/var/lib/chroot-distro/containers"
	else
		dir="${XDG_DATA_HOME:-${HOME}/.local/share}/chroot-distro/containers"
	fi
	if [[ -d "${dir}" ]]; then
		local d
		for d in "${dir}"/*/; do
			[[ -d "${d}rootfs" ]] && printf '%s\n' "${d%/}" | sed 's|.*/||'
		done
	fi
}

# Returns 0 (true) when running on Termux/Android: at least two of three
# independent indicators must match, mirroring _detect_termux() in constants.py.
_chroot_distro_is_termux() {
	local score=0
	[[ -f /system/build.prop || -d /data/app ]] && ((score++))
	[[ -n "${TERMUX_APP__APP_VERSION_NAME}" || -n "${TERMUX_VERSION}" ]] && ((score++))
	local prefix="${TERMUX__PREFIX:-/data/data/com.termux/files/usr}"
	[[ -r "${prefix}" && -x "${prefix}" ]] && ((score++))
	[[ ${score} -ge 2 ]]
}

# Populate COMPREPLY from compgen -W without word-splitting (shellcheck SC2207).
_chroot_distro_compgen_words() {
	mapfile -t COMPREPLY < <(compgen -W "$1" -- "$2")
}

_chroot_distro() {
	local cur prev words cword
	_init_completion || return

	local -r _all_commands="install add i in ins remove rm rename reset login sh list li ls
        backup bak bkp restore clear-cache clear cl copy cp sync run build push
        unmount umount um help h he hel"

	# Complete the subcommand itself
	if [[ ${cword} -eq 1 ]]; then
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-h --help --no-elevate --use-sudo" "${cur}"
		else
			_chroot_distro_compgen_words "${_all_commands}" "${cur}"
		fi
		return
	fi

	local command="${words[1]}"

	# Map aliases to canonical command names (mirrors parser.py ALIAS_TO_CANONICAL)
	case "${command}" in
	add | i | in | ins) command=install ;;
	rm) command=remove ;;
	sh) command=login ;;
	li | ls) command=list ;;
	bak | bkp) command=backup ;;
	clear | cl) command=clear-cache ;;
	cp) command=copy ;;
	umount | um) command=unmount ;;
	h | he | hel) command=help ;;
	esac

	case "${command}" in

	# -----------------------------------------------------------------------
	install)
		case "${prev}" in
		-n | --name | --override-alias)
			return
			;;
		-a | --architecture)
			_chroot_distro_compgen_words "aarch64 arm i686 riscv64 x86_64" "${cur}"
			return
			;;
		esac
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-n --name --override-alias -a --architecture -q --quiet -h --help" "${cur}"
		elif [[ "${cur}" == /* || "${cur}" == ./* || "${cur}" == ../* ]]; then
			_filedir
		fi
		;;

	# -----------------------------------------------------------------------
	remove)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-v --verbose -q --quiet -h --help" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	rename)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-q --quiet -h --help" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	reset)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-q --quiet -h --help" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	login)
		# After --, complete host-side commands
		local i
		for ((i = 2; i < cword; i++)); do
			if [[ "${words[i]}" == "--" ]]; then
				_command_offset $((i + 1))
				return
			fi
		done
		case "${prev}" in
		-u | --user) return ;;
		-b | --bind)
			_filedir
			return
			;;
		--hostname) return ;;
		-w | --work-dir)
			_filedir -d
			return
			;;
		-e | --env) return ;;
		esac
		if [[ "${cur}" == -* ]]; then
			local opts="-u --user --isolated --minimal --shared-home --shared-tmp --shared-x11
                    -b --bind --hostname -w --work-dir -e --env --get-chroot-cmd -h --help"
			_chroot_distro_compgen_words "${opts}" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	list)
		_chroot_distro_compgen_words "-q --quiet -h --help" "${cur}"
		;;

	# -----------------------------------------------------------------------
	backup)
		case "${prev}" in
		-o | --output)
			_filedir
			return
			;;
		-c | --compress)
			_chroot_distro_compgen_words "gzip bzip2 xz none" "${cur}"
			return
			;;
		esac
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-o --output -c --compress -v --verbose -q --quiet -h --help" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	restore)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-v --verbose -q --quiet -h --help" "${cur}"
		else
			_filedir '@(tar|tar.gz|tgz|tar.bz2|tbz2|tar.xz|txz)'
		fi
		;;

	# -----------------------------------------------------------------------
	clear-cache)
		_chroot_distro_compgen_words "-v --verbose -q --quiet -h --help" "${cur}"
		;;

	# -----------------------------------------------------------------------
	copy)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-v --verbose -q --quiet -m --move -r --recursive -h --help" "${cur}"
		else
			# Support container:path notation: complete container names
			# (no colon yet) or paths (colon already present → filesystem)
			if [[ "${cur}" == *:* ]]; then
				_filedir
			else
				local containers
				containers=$(_chroot_distro_get_containers)
				_chroot_distro_compgen_words "${containers}" "${cur}"
				# Also allow plain host paths
				local -a files
				_filedir
				COMPREPLY+=("${files[@]}")
			fi
		fi
		;;

	# -----------------------------------------------------------------------
	sync)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-v --verbose -q --quiet -c --checksum -d --delete -h --help" "${cur}"
		else
			if [[ "${cur}" == *:* ]]; then
				_filedir
			else
				local containers
				containers=$(_chroot_distro_get_containers)
				_chroot_distro_compgen_words "${containers}" "${cur}"
				local -a files
				_filedir
				COMPREPLY+=("${files[@]}")
			fi
		fi
		;;

	# -----------------------------------------------------------------------
	run)
		# After --, complete host-side commands
		local i
		for ((i = 2; i < cword; i++)); do
			if [[ "${words[i]}" == "--" ]]; then
				_command_offset $((i + 1))
				return
			fi
		done
		case "${prev}" in
		-u | --user) return ;;
		-b | --bind)
			_filedir
			return
			;;
		--hostname) return ;;
		-w | --work-dir)
			_filedir -d
			return
			;;
		-e | --env) return ;;
		esac
		if [[ "${cur}" == -* ]]; then
			local opts="-u --user --isolated --minimal --shared-home --shared-tmp --shared-x11
                    -b --bind --hostname -w --work-dir -e --env --get-chroot-cmd -h --help"
			_chroot_distro_compgen_words "${opts}" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	unmount)
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-h --help" "${cur}"
		else
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	build)
		case "${prev}" in
		-f | --file)
			_filedir
			return
			;;
		-t | --tag)
			return
			;;
		--build-arg)
			return
			;;
		-a | --architecture)
			_chroot_distro_compgen_words "aarch64 arm i686 riscv64 x86_64" "${cur}"
			return
			;;
		--target)
			return
			;;
		-o | --output)
			_filedir
			return
			;;
		--install-as)
			_chroot_distro_compgen_words "$(_chroot_distro_get_containers)" "${cur}"
			return
			;;
		esac
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-f --file -t --tag --build-arg -a --architecture
                    --target -o --output --install-as --no-cache
                    -v --verbose -q --quiet -h --help" "${cur}"
		else
			_filedir -d
		fi
		;;

	# -----------------------------------------------------------------------
	push)
		case "${prev}" in
		-a | --architecture)
			_chroot_distro_compgen_words "aarch64 arm i686 riscv64 x86_64" "${cur}"
			return
			;;
		esac
		if [[ "${cur}" == -* ]]; then
			_chroot_distro_compgen_words "-a --architecture -q --quiet -h --help" "${cur}"
		fi
		;;

	# -----------------------------------------------------------------------
	help)
		local topics="install remove rename reset login list backup restore clear-cache copy sync run build push unmount"
		_chroot_distro_compgen_words "${topics}" "${cur}"
		;;

	esac
}

complete -F _chroot_distro chroot-distro
