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

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

COMFYUI_SYMLINK="${EROOT}/usr/bin/comfyui"
COMFYUI_DIR="${EROOT}/opt"

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

get_active() {
	if [[ -L "${COMFYUI_SYMLINK}" ]]; then
		local target
		target=$(readlink -f "${COMFYUI_SYMLINK}")
		local variant
		variant=$(echo "${target}" | sed -n 's|.*/comfyui-\([^/]*\)/bin/comfyui|\1|p')
		echo "${variant}"
	fi
}

remove_symlinks() {
	rm -f "${COMFYUI_SYMLINK}" || die
}

set_symlinks() {
	local target="${1}"
	local bin="${COMFYUI_DIR}/comfyui-${target}/bin/comfyui"

	if [[ ! -x "${bin}" ]]; then
		die -q "Target '${target}' not found or not executable: ${bin}"
	fi

	ln -s "${bin}" "${COMFYUI_SYMLINK}" || die

	# Also set direct access symlinks
	local variant
	for f in "${COMFYUI_DIR}"/comfyui-*/bin/comfyui; do
		[[ -x "${f}" ]] || continue
		variant=$(echo "${f}" | sed -n 's|.*/comfyui-\([^/]*\)/bin/comfyui|\1|p')
		ln -sf "${f}" "${EROOT}/usr/bin/comfyui-${variant}" || die
	done
}

### list action ###

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

do_list() {
	local targets
	local active
	active=$(get_active)

	write_list_start "Available ComfyUI backends:"

	local f variant i=1
	for f in "${COMFYUI_DIR}"/comfyui-*/bin/comfyui; do
		[[ -x "${f}" ]] || continue
		variant=$(echo "${f}" | sed -n 's|.*/comfyui-\([^/]*\)/bin/comfyui|\1|p')
		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)
	if [[ -n "${active}" ]]; then
		echo "${active}"
	else
		echo "(unset)"
	fi
}

### set action ###

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

describe_set_parameters() {
	echo "<target>"
}

describe_set_options() {
	echo "target : Backend name (rocm, cuda) or number from 'list'"
}

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

	local target="${1}"

	# Support numeric selection
	if is_number "${target}"; then
		local targets=()
		local f variant
		for f in "${COMFYUI_DIR}"/comfyui-*/bin/comfyui; do
			[[ -x "${f}" ]] || continue
			variant=$(echo "${f}" | sed -n 's|.*/comfyui-\([^/]*\)/bin/comfyui|\1|p')
			targets+=("${variant}")
		done
		target="${targets[$((${1} - 1))]}"
		[[ -z "${target}" ]] && die -q "Invalid selection"
	fi

	remove_symlinks
	set_symlinks "${target}"
}
