# Copyright 2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

DESCRIPTION="Manage ComfyUI backend (ROCm/CUDA)"
VERSION="0.2"

COMFYUI_DIR="${EROOT}/usr/lib/comfyui"

find_targets() {
	local targets=()
	local d
	for d in "${COMFYUI_DIR}"/*/; do
		[[ -d "${d}" ]] && targets+=("$(basename "${d}")")
	done
	echo "${targets[@]}"
}

get_active() {
	if [[ -L "${EROOT}/usr/bin/comfyui" ]]; then
		local target
		target=$(readlink "${EROOT}/usr/bin/comfyui")
		target=${target#../lib/comfyui/}
		target=${target%%/*}
		echo "${target}"
	fi
}

remove_symlinks() {
	rm -f "${EROOT}/usr/bin/comfyui"
	local d
	for d in "${COMFYUI_DIR}"/*/bin/*; do
		local name="$(basename "${d}")"
		[[ -L "${EROOT}/usr/bin/${name}" ]] && rm -f "${EROOT}/usr/bin/${name}"
	done
}

set_symlinks() {
	local target="${1}"
	local prefix="${COMFYUI_DIR}/${target}"

	if [[ ! -d "${prefix}/bin" ]]; then
		die -q "Target '${target}' not found: ${prefix}/bin"
	fi

	# Main comfyui symlink points to the selected backend
	local main_bin="${prefix}/bin/comfyui-${target}"
	[[ -x "${main_bin}" ]] && \
		ln -s "../lib/comfyui/${target}/bin/comfyui-${target}" "${EROOT}/usr/bin/comfyui"

	# Per-backend symlinks (comfyui-rocm, comfyui-cuda) for direct access
	local f
	for f in "${COMFYUI_DIR}"/*/bin/*; do
		[[ -x "${f}" ]] || continue
		local name="$(basename "${f}")"
		ln -sf "../lib/comfyui/$(basename "$(dirname "$(dirname "${f}")")")/bin/${name}" \
			"${EROOT}/usr/bin/${name}"
	done
}

### list action ###

describe_list() {
	echo "List available ComfyUI backends"
}

do_list() {
	local active
	active=$(get_active)
	write_list_start "Available ComfyUI backends:"

	local d i=1
	for d in "${COMFYUI_DIR}"/*/; do
		[[ -d "${d}" ]] || continue
		local variant="$(basename "${d}")"
		if [[ "${variant}" == "${active}" ]]; then
			write_kv_list_entry "[${i}]" "${variant} *"
		else
			write_kv_list_entry "[${i}]" "${variant}"
		fi
		((i++))
	done
}

### show action ###

describe_show() {
	echo "Show currently active ComfyUI backend"
}

do_show() {
	local active
	active=$(get_active)
	echo "${active:-"(unset)"}"
}

### set action ###

describe_set() {
	echo "Set active ComfyUI backend"
}

describe_set_parameters() {
	echo "<target>"
}

do_set() {
	[[ -z "${1}" ]] && die -q "You must specify a backend (rocm, cuda)"

	local target="${1}"

	if is_number "${target}"; then
		local targets=( $(find_targets) )
		target="${targets[$((${1} - 1))]}"
		[[ -z "${target}" ]] && die -q "Invalid selection"
	fi

	remove_symlinks
	set_symlinks "${target}"
}
