# Maintainer: Sarah Ottinger <schalaalexiazeal@gmail.com>

_realname=llvmlite
pkgbase=mingw-w64-python-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-python-${_realname}")
pkgver=0.46.0
pkgrel=3
pkgdesc='Lightweight LLVM python binding for writing JIT compilers (mingw-w64)'
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
msys2_references=(
  'purl: pkg:pypi/llvmlite'
)
url="https://github.com/numba/llvmlite"
license=('spdx:BSD-2-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-python"
         "${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-zstd")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-build"
             "${MINGW_PACKAGE_PREFIX}-python-installer"
             "${MINGW_PACKAGE_PREFIX}-python-setuptools"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-llvm-20"
             "${MINGW_PACKAGE_PREFIX}-compiler-rt-20")
source=("https://pypi.org/packages/source/${_realname::1}/${_realname}/${_realname}-${pkgver}.tar.gz"
        "path_fix.patch")
sha256sums=('227c9fd6d09dce2783c18b754b7cd9d9b3b3515210c46acc2d3c5badd9870ceb'
            '9a3869fdd80c47a2a2fcbc1332b1b15aa9de85c669b22ce427f3c33ba9a193ad')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Nbp1 -i "${srcdir}/$_patch"
  done
}

prepare() {
  cd "${_realname}-${pkgver}"

  apply_patch_with_msg \
    path_fix.patch

  sed -i "s,_MSC_VER,_WIN32," ffi/core.h
}

build() {
  cp -r "${_realname}-${pkgver}" "python-build-${MSYSTEM}" && cd "python-build-${MSYSTEM}"

  export CMAKE_GENERATOR="Ninja"
  export LLVM_DIR=${MINGW_PREFIX}/opt/llvm-20/lib/cmake/llvm
  if [[ ${CC} == gcc ]]; then
    export LLVMLITE_LTO=off
  fi

  python -m build --wheel --skip-dependency-check --no-isolation
}

package() {
  cd "python-build-${MSYSTEM}"

  MSYS2_ARG_CONV_EXCL="--prefix=" \
    python -m installer --prefix=${MINGW_PREFIX} \
    --destdir="${pkgdir}" dist/*.whl

  local _py3ver=$(python -c "import sys;sys.stdout.write('.'.join(map(str, sys.version_info[:2])))")
  install -Dm644 ffi/build/libllvmlite.dll "${pkgdir}${MINGW_PREFIX}/lib/python${_py3ver}/site-packages/llvmlite/binding/llvmlite.dll"

  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/python-${_realname}/LICENSE"
}
