import { spawn } from 'node:child_process'
import { resolve } from 'node:path'
import process from 'node:process'

const projectRoot = process.cwd()
const uniCli = resolve(projectRoot, 'node_modules/@dcloudio/vite-plugin-uni/bin/uni.js')

// Some macOS sessions expose a low launchd file-watch limit even when the
// shell's ulimit is high. Polling keeps uni-app builds reliable in that case.
const child = spawn(process.execPath, [uniCli, ...process.argv.slice(2)], {
  cwd: projectRoot,
  env: {
    ...process.env,
    CHOKIDAR_USEPOLLING: process.env.CHOKIDAR_USEPOLLING || '1',
  },
  stdio: 'inherit',
})

child.on('error', (error) => {
  console.error(`无法启动 uni-app CLI：${error.message}`)
  process.exit(1)
})

child.on('exit', (code, signal) => {
  if (signal) {
    process.kill(process.pid, signal)
    return
  }

  process.exit(code ?? 1)
})
