_realname=gemini-cli
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.19.4
pkgrel=1
pkgdesc="An open-source AI agent that brings the power of Gemini directly into your terminal. (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/google-gemini/gemini-cli"
msys2_references=(
  'archlinux: gemini-cli'
  'aur: gemini-cli'
  'purl: pkg:npm/@google/gemini-cli'
)
license=('Apache-2.0')
depends=(${MINGW_PACKAGE_PREFIX}-nodejs)
makedepends=(${MINGW_PACKAGE_PREFIX}-cc)
source=("https://registry.npmjs.org/@google/$_realname/-/$_realname-$pkgver.tgz"
        "tree-sitter-bash-mingw-fix.patch"
        "node-pty-support-to-build-with-mingw-w64-in-windows.patch"
        "node-pty-fix-type-errors.patch"
        "node-pty-fix-windows-arm-defs.patch")
sha256sums=('2ae7ab76decd7133d2fd72993860e5860c4fcbe3b570855de73db11cb417b4b5'
            '78a7e0a5579e236c3565e60b297a3ec8206a6b5dd81642029a37239d2fd9d104'
            'd68987126a3ca395c042f0513ecef0ae0de3a8813fe4023334f764f74e786aa1'
            '0afd76a0332c7ae8700622b7517d03dfea0ee308ca444d0b64a7ebd07bc78b80'
            '452c8b12820ca1ec206727ec2d68eb30b47d83a03088301598534029ef551b98')
noextract=("${_realname}-${pkgver}.tgz")

package() {
  # Install with --ignore-scripts first to download dependencies without building
  npm install -g \
    --cache npm-cache \
    --prefix "${pkgdir}${MINGW_PREFIX}" \
    --ignore-scripts \
    "${_realname}-${pkgver}.tgz"

  # Patch tree-sitter-bash for MinGW compatibility
  local _node_modules_dir="${pkgdir}${MINGW_PREFIX}/lib/node_modules/@google/gemini-cli/node_modules"
  # https://github.com/tree-sitter/tree-sitter-bash/pull/314
  patch -Np1 -d "${_node_modules_dir}/tree-sitter-bash" -i "${srcdir}/tree-sitter-bash-mingw-fix.patch"
  # https://github.com/microsoft/node-pty/pull/828
  patch -Np1 -d "${_node_modules_dir}/node-pty" -i "${srcdir}/node-pty-support-to-build-with-mingw-w64-in-windows.patch"
  # Backport type error fixes for winpty
  patch -Np1 -d "${_node_modules_dir}/node-pty" -i "${srcdir}/node-pty-fix-type-errors.patch"
  # Fix Windows ARM definitions
  patch -Np1 -d "${_node_modules_dir}/node-pty" -i "${srcdir}/node-pty-fix-windows-arm-defs.patch"

  # Run install scripts
  npm rebuild \
    --prefix "${pkgdir}${MINGW_PREFIX}/lib/node_modules/@google/gemini-cli"
}
