#!/usr/bin/env node

import { accessSync, constants } from 'node:fs'
import { spawn } from 'node:child_process'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const binDir = dirname(fileURLToPath(import.meta.url))
const packageDir = dirname(binDir)
const binaryName = process.platform === 'win32' ? 'turing.exe' : 'turing'
const binaryPath = join(packageDir, 'vendor', binaryName)

try {
  accessSync(binaryPath, constants.F_OK)
} catch {
  console.error('错误：Turing Code 二进制不存在，请重新执行 npm 安装。')
  process.exit(1)
}

const child = spawn(binaryPath, process.argv.slice(2), {
  stdio: 'inherit',
})

child.on('exit', code => {
  process.exit(code ?? 1)
})

child.on('error', error => {
  console.error(`错误：启动 Turing Code 失败：${error instanceof Error ? error.message : String(error)}`)
  process.exit(1)
})
