_realname=gemini-cli
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.21.2
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=(git
             ${MINGW_PACKAGE_PREFIX}-cc
             ${MINGW_PACKAGE_PREFIX}-jq)
source=("git+$url.git#tag=v$pkgver"
        "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=('83c498c3f33578dc1885fd949ee10490cc8f97f34291f0eb67ae07f0fbff9263'
            '78a7e0a5579e236c3565e60b297a3ec8206a6b5dd81642029a37239d2fd9d104'
            'd68987126a3ca395c042f0513ecef0ae0de3a8813fe4023334f764f74e786aa1'
            '0afd76a0332c7ae8700622b7517d03dfea0ee308ca444d0b64a7ebd07bc78b80'
            '452c8b12820ca1ec206727ec2d68eb30b47d83a03088301598534029ef551b98')

prepare() {
  cd $_realname
  npm clean-install --ignore-scripts

  # Patch tree-sitter-bash for MinGW compatibility
  local _node_modules_dir="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"
}

build() {
  cd $_realname
  npm run bundle
  local bundled=$(jq '.dependencies + .optionalDependencies | keys' package.json)
  npm pkg set --json bundledDependencies="$bundled"
  npm pack
}

check() {
  cd $_realname
  npm run build
  npm test
}

package() {
  cd $_realname
  npm install --global --offline --prefix "${pkgdir}${MINGW_PREFIX}" \
    google-$_realname-$pkgver.tgz
  install -vDm644 -t "${pkgdir}${MINGW_PREFIX}/share/doc/$_realname" README.md
  install -vDm644 -t "${pkgdir}${MINGW_PREFIX}/share/licenses/$_realname" LICENSE
}
