# Maintainer: dax
# Maintainer: adam

pkgname='opencode'
pkgver=1.0.57
_subver=
options=('!debug' '!strip')
pkgrel=1
pkgdesc='The AI coding agent built for the terminal.'
url='https://github.com/sst/opencode'
arch=('aarch64' 'x86_64')
license=('MIT')
provides=('opencode')
conflicts=('opencode-bin')
depends=('fzf' 'ripgrep')
makedepends=('git' 'bun-bin' 'go' 'npm')

source=("opencode-${pkgver}.tar.gz::https://github.com/sst/opencode/archive/v${pkgver}${_subver}.tar.gz")
sha256sums=('SKIP')

build() {
  cd "opencode-${pkgver}"
  
  # Ensure npm is in PATH for bun's shell
  export PATH="/usr/bin:$PATH"
  
  # Install workspace dependencies from root
  bun install
  
  # The build script uses relative imports like ../node_modules/...
  # Create symlink so packages/opencode/node_modules points to root node_modules
  cd packages/opencode
  ln -sf ../../node_modules node_modules
  
  # Build the binary
  OPENCODE_CHANNEL=latest OPENCODE_VERSION=${pkgver} bun run build --single
}

package() {
  cd "opencode-${pkgver}/packages/opencode"
  
  # Find the appropriate binary for this architecture
  case "${CARCH}" in
    x86_64)
      binary=$(find dist/opencode-linux-x64*/bin/opencode -type f | head -1)
      ;;
    aarch64)
      binary=$(find dist/opencode-linux-arm64*/bin/opencode -type f | head -1)
      ;;
  esac
  
  install -Dm755 "${binary}" "${pkgdir}/usr/bin/opencode"
}
