# Copyright 2022-2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
# CUDA implementation of PyTorch Python bindings

EAPI=8

DISTUTILS_USE_PEP517=setuptools
PYTHON_COMPAT=( python3_{11..14} )
DISTUTILS_SINGLE_IMPL=1
DISTUTILS_EXT=1
inherit distutils-r1 prefix

MY_PN=pytorch
MYPN=pytorch
MYP=${MYPN}-${PV}

DESCRIPTION="Tensors and Dynamic neural networks in Python (CUDA backend)"
HOMEPAGE="https://pytorch.org/"
SRC_URI="https://github.com/pytorch/${MYPN}/archive/refs/tags/v${PV}.tar.gz -> ${MYP}.tar.gz"

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

LICENSE="BSD"
SLOT="0"
KEYWORDS="~amd64"
RESTRICT="test"

REQUIRED_USE=${PYTHON_REQUIRED_USE}

CAFFE2_PREFIX="/usr/lib/caffe2/cuda"
PYTORCH_PREFIX="/usr/lib/pytorch/cuda"

RDEPEND="
	${PYTHON_DEPS}
	~sci-ml/caffe2-cuda-${PV}[${PYTHON_SINGLE_USEDEP}]
	app-eselect/eselect-pytorch
	$(python_gen_cond_dep '
		dev-python/sympy[${PYTHON_USEDEP}]
		dev-python/typing-extensions[${PYTHON_USEDEP}]
	')
"
DEPEND="${RDEPEND}
	$(python_gen_cond_dep '
		dev-python/pyyaml[${PYTHON_USEDEP}]
	')
"

PATCHES=(
	"${FILESDIR}"/${MY_PN}-2.9.0-dontbuildagain.patch
	"${FILESDIR}"/${MY_PN}-2.10.0-cpp-extension-multilib.patch
)

src_prepare() {
	sed -e "s|%LIB_DIR%|$(get_libdir)|g" \
		-i torch/utils/cpp_extension.py || die
	sed -e "/BUILD_DIR/s|build|/var/lib/caffe2-cuda/|" \
		-i tools/setup_helpers/env.py || die
	sed -e "/build-backend/s|:__legacy__||" \
		-i pyproject.toml || die
	distutils-r1_src_prepare
	hprefixify tools/setup_helpers/env.py
}

python_compile() {
	PYTORCH_BUILD_VERSION=${PV} \
	PYTORCH_BUILD_NUMBER=0 \
	USE_SYSTEM_LIBS=ON \
	CMAKE_BUILD_DIR="${BUILD_DIR}" \
	distutils-r1_python_compile develop sdist
}

python_install() {
	local dest="${ED}${PYTORCH_PREFIX}"
	mkdir -p "${dest}" || die
	USE_SYSTEM_LIBS=ON distutils-r1_python_install
	local sitedir="$(python_get_sitedir)"
	for item in torch functorch torchgen; do
		if [[ -d "${ED}${sitedir}/${item}" ]]; then
			mv "${ED}${sitedir}/${item}" "${dest}/${item}" || die
		fi
	done

	# Move dist-info to prefix to avoid collisions with other backends
	local distinfo
	for distinfo in "${ED}${sitedir}"/torch-*.dist-info; do
		[[ -d "${distinfo}" ]] && mv "${distinfo}" "${dest}/" || true
	done
	if [[ -f "${ED}/usr/bin/torchrun" ]]; then
		dodir "${PYTORCH_PREFIX}/bin"
		mv "${ED}/usr/bin/torchrun" "${ED}${PYTORCH_PREFIX}/bin/torchrun" || die
	fi

	# torch/lib symlinks to caffe2 prefix — native lib resolution without env vars
	dodir "${PYTORCH_PREFIX}/torch/lib"
	local caffe2lib="${CAFFE2_PREFIX}/$(get_libdir)"
	local lib
	for lib in "${ED}${caffe2lib}"/*.so; do
		[[ -f "${lib}" ]] || continue
		local bname="$(basename "${lib}")"
		dosym "${caffe2lib}/${bname}" "${PYTORCH_PREFIX}/torch/lib/${bname}"
	done
}

pkg_postinst() {
	local active
	active=$(eselect pytorch show 2>/dev/null)
	if [[ "${active}" == "(unset)" || -z "${active}" ]]; then
		eselect pytorch set cuda
		elog "PyTorch backend set to: cuda"
	fi
}