# Copyright 2022-2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
# CUDA implementation of PyTorch Python bindings
# Python wrapper only — C++ backend is provided by sci-ml/caffe2-cuda

EAPI=8

DISTUTILS_USE_PEP517=setuptools
PYTHON_COMPAT=( python3_{12..15} )
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}
	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}]
	')
"

src_prepare() {
	# Replace scikit-build-core with setuptools — we don't run cmake,
	# caffe2-cuda already built the C++ backend
	cat > pyproject.toml <<-'PYPROJECT' || die
	[build-system]
	requires = ["setuptools"]
	build-backend = "setuptools.build_meta"

	[project]
	name = "torch"
	version = "${PV}"
	requires-python = ">=3.11"

	[tool.setuptools.packages.find]
	include = ["torch*", "torchgen*", "functorch*"]
	PYPROJECT
	sed -i "s/\${PV}/${PV}/" pyproject.toml || die

	# Create setup.py — installs Python packages without cmake
	cat > setup.py <<-'SETUP' || die
	from setuptools import setup, find_packages
	setup(
	    name="torch",
	    packages=find_packages(include=["torch*", "torchgen*", "functorch*"]),
	    package_data={"torch": ["py.typed", "**/*.pyi", "**/*.h", "**/*.hpp"]},
	)
	SETUP

	# Generate version.py from template
	local _cuda_version="$(nvcc --version 2>/dev/null | grep -oP 'release \K[0-9.]+')"
	cat > torch/version.py <<-VERSIONPY || die
	__version__ = '${PV}'
	debug = False
	cuda = '${_cuda_version}'
	git_version = 'unknown'
	hip = None
	VERSIONPY

	# Multilib fix for cpp_extension.py
	sed -e "s|'lib'|'$(get_libdir)'|g" \
		-i torch/utils/cpp_extension.py || die

	distutils-r1_src_prepare
	hprefixify torch/utils/cpp_extension.py
}

python_compile() {
	PYTORCH_BUILD_VERSION=${PV} \
	PYTORCH_BUILD_NUMBER=0 \
	distutils-r1_python_compile
}

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

	# Move dist-info to prefix, symlink back for importlib.metadata discovery
	local distinfo
	for distinfo in "${ED}${sitedir}"/torch-*.dist-info; do
		[[ -d "${distinfo}" ]] || continue
		local dibase="$(basename "${distinfo}")"
		rm -rf "${dest}/${dibase}"
		mv "${distinfo}" "${dest}/" || die
		if [[ ! -L "${EROOT}${sitedir}/${dibase}" ]]; then
			dosym "${PYTORCH_PREFIX}/${dibase}" "${sitedir}/${dibase}"
		fi
	done
	if [[ -f "${ED}/usr/bin/torchrun" ]]; then
		dodir "${PYTORCH_PREFIX}/bin"
		rm -f "${ED}${PYTORCH_PREFIX}/bin/torchrun"
		mv "${ED}/usr/bin/torchrun" "${ED}${PYTORCH_PREFIX}/bin/torchrun" || die
	fi

	# lib symlinks — skip files already owned by caffe2-cuda
	local caffe2lib="${CAFFE2_PREFIX}/$(get_libdir)"
	local lib
	for lib in "${EROOT}${caffe2lib}"/*.so; do
		[[ -f "${lib}" ]] || continue
		local bname="$(basename "${lib}")"
		local target="${PYTORCH_PREFIX}/torch/lib/${bname}"
		[[ -L "${EROOT}${target}" ]] && continue
		dosym "${caffe2lib}/${bname}" "${target}"
	done

	# _C extension from caffe2 prefix
	local cext
	for cext in "${EROOT}${CAFFE2_PREFIX}"/_C*.so; do
		[[ -f "${cext}" ]] || continue
		local cname="$(basename "${cext}")"
		dosym "${CAFFE2_PREFIX}/${cname}" "${PYTORCH_PREFIX}/torch/${cname}"
	done

	# Per-Python-version lib dirs — RUNPATH in _C.so uses $ORIGIN/py3XX
	# which resolves to the symlink path (pytorch prefix), not the real path
	# (caffe2 prefix). These symlinks bridge the gap.
	local _pydir
	for _pydir in "${EROOT}${CAFFE2_PREFIX}"/py3*/; do
		[[ -d "${_pydir}" ]] || continue
		local _dirname="$(basename "${_pydir}")"
		dosym "${CAFFE2_PREFIX}/${_dirname}" "${PYTORCH_PREFIX}/torch/${_dirname}"
	done
	dosym "${CAFFE2_PREFIX}/$(get_libdir)" "${PYTORCH_PREFIX}/torch/$(get_libdir)"
}

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
	elog ""
	elog "Both ROCm and CUDA backends can be installed simultaneously."
	elog "Use 'eselect pytorch set <rocm|cuda>' to switch the default."
	elog "To use a specific backend per process without changing the default:"
	elog "  PYTHONPATH=/usr/lib/pytorch/rocm:\$PYTHONPATH python3 script.py"
	elog "  PYTHONPATH=/usr/lib/pytorch/cuda:\$PYTHONPATH python3 script.py"
}