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

EAPI=8

PYTHON_COMPAT=( python3_{12..14} )
DISTUTILS_SINGLE_IMPL=1

inherit python-single-r1

MY_PN=ComfyUI
MY_P=${MY_PN}-${PV}

DESCRIPTION="Diffusion model GUI and backend (CUDA)"
HOMEPAGE="https://www.comfy.org/ https://github.com/comfyanonymous/ComfyUI"
SRC_URI="https://github.com/comfyanonymous/${MY_PN}/archive/refs/tags/v${PV}.tar.gz -> ${MY_P}.tar.gz"

S="${WORKDIR}/${MY_P}"

LICENSE="GPL-3"
SLOT="0"
KEYWORDS="~amd64"
REQUIRED_USE="${PYTHON_REQUIRED_USE}"

COMFYUI_PREFIX="/usr/lib/comfyui/cuda"
PYTORCH_PREFIX="/usr/lib/pytorch/cuda"
TORCHVISION_PREFIX="/usr/lib/torchvision/cuda"

RDEPEND="
	${PYTHON_DEPS}
	app-eselect/eselect-comfyui
	sci-ml/pytorch-cuda[${PYTHON_SINGLE_USEDEP}]
	sci-ml/torchvision-cuda[${PYTHON_SINGLE_USEDEP}]
	sci-ml/transformers[${PYTHON_SINGLE_USEDEP}]
	sci-ml/tokenizers[${PYTHON_SINGLE_USEDEP}]
	dev-python/comfy-kitchen[${PYTHON_SINGLE_USEDEP}]
	dev-python/comfy-aimdo[${PYTHON_SINGLE_USEDEP}]
	dev-python/torchsde[${PYTHON_SINGLE_USEDEP}]
	dev-python/kornia[${PYTHON_SINGLE_USEDEP}]
	dev-python/spandrel[${PYTHON_SINGLE_USEDEP}]
	$(python_gen_cond_dep '
		sci-ml/sentencepiece[${PYTHON_USEDEP}]
		sci-ml/safetensors[${PYTHON_USEDEP}]
		dev-python/numpy[${PYTHON_USEDEP}]
		dev-python/einops[${PYTHON_USEDEP}]
		dev-python/aiohttp[${PYTHON_USEDEP}]
		dev-python/yarl[${PYTHON_USEDEP}]
		dev-python/pyyaml[${PYTHON_USEDEP}]
		dev-python/pillow[${PYTHON_USEDEP}]
		dev-python/scipy[${PYTHON_USEDEP}]
		dev-python/tqdm[${PYTHON_USEDEP}]
		dev-python/psutil[${PYTHON_USEDEP}]
		dev-python/alembic[${PYTHON_USEDEP}]
		dev-python/sqlalchemy[${PYTHON_USEDEP}]
		dev-python/filelock[${PYTHON_USEDEP}]
		dev-python/av[${PYTHON_USEDEP}]
		dev-python/requests[${PYTHON_USEDEP}]
		dev-python/simpleeval[${PYTHON_USEDEP}]
		dev-python/blake3[${PYTHON_USEDEP}]
		dev-python/pydantic[${PYTHON_USEDEP}]
		dev-python/pydantic-settings[${PYTHON_USEDEP}]
		dev-python/comfyui-frontend-package[${PYTHON_USEDEP}]
		dev-python/comfyui-workflow-templates[${PYTHON_USEDEP}]
		dev-python/comfyui-embedded-docs[${PYTHON_USEDEP}]
	')
"

src_install() {
	local dest="${COMFYUI_PREFIX}"
	local pyver="${EPYTHON#python}"

	# Application code
	insinto "${dest}/share/comfyui"
	doins -r comfy comfy_api comfy_api_nodes comfy_config comfy_execution comfy_extras
	doins -r app api_server blueprints middleware utils
	doins -r alembic_db
	doins main.py server.py execution.py folder_paths.py nodes.py
	doins node_helpers.py latent_preview.py cuda_malloc.py
	doins comfyui_version.py protocol.py new_updater.py hook_breaker_ac10a0.py
	doins pyproject.toml alembic.ini

	# Prefix site-packages with dependency symlinks — no env vars needed
	dodir "${dest}/lib/python${pyver}/site-packages"
	dosym "${PYTORCH_PREFIX}/torch" "${dest}/lib/python${pyver}/site-packages/torch"
	dosym "${TORCHVISION_PREFIX}/torchvision" "${dest}/lib/python${pyver}/site-packages/torchvision"

	# .pth for system site-packages (numpy, PIL, aiohttp, etc.)
	echo "/usr/lib/python${pyver}/site-packages" \
		> "${ED}/${dest}/lib/python${pyver}/site-packages/system-deps.pth"

	# Self-contained launcher — uses site.addsitedir for own prefix only
	cat > "${T}/comfyui-cuda" <<-LAUNCHER
	#!/usr/bin/env python${pyver}
	import sys, os, site
	_prefix = "${dest}"
	_app = os.path.join(_prefix, "share", "comfyui")
	_sp = os.path.join(_prefix, "lib", "python${pyver}", "site-packages")
	sys.path.insert(0, _sp)
	site.addsitedir(_sp)
	sys.path.insert(0, _app)
	os.chdir(_app)
	exec(compile(open(os.path.join(_app, "main.py")).read(), "main.py", "exec"))
	LAUNCHER
	exeinto "${dest}/bin"
	doexe "${T}/comfyui-cuda"

	# Direct access symlink
	dosym "${dest}/bin/comfyui-cuda" "/usr/bin/comfyui-cuda"

	# Shared data dirs
	keepdir /var/lib/comfyui/models
	keepdir /var/lib/comfyui/custom_nodes
	keepdir /var/lib/comfyui/output
	keepdir /var/lib/comfyui/input
}

pkg_postinst() {
	local active
	active=$(eselect comfyui show 2>/dev/null)
	if [[ "${active}" == "(unset)" || -z "${active}" ]]; then
		eselect comfyui set cuda
		elog "ComfyUI backend set to: cuda"
	fi
	elog "ComfyUI (CUDA) installed to ${COMFYUI_PREFIX}"
	elog "Run: comfyui-cuda --listen 0.0.0.0 --port 8189"
}