#!/usr/bin/env node
/**
 * npm 全局 CLI 启动器：按当前 OS/ARCH 选择 optional 平台子包中的 standalone 二进制并执行。
 */

import { spawnSync } from 'node:child_process'
import { createRequire } from 'node:module'
import { buildLauncherEnv } from '../lib/launcher-env.js'

const PLATFORM_PACKAGES = [
  { id: 'linux-x64', pkg: '@auto-ai/agent-linux-x64', bin: 'agent' },
  { id: 'linux-arm64', pkg: '@auto-ai/agent-linux-arm64', bin: 'agent' },
  { id: 'darwin-x64', pkg: '@auto-ai/agent-darwin-x64', bin: 'agent' },
  { id: 'darwin-arm64', pkg: '@auto-ai/agent-darwin-arm64', bin: 'agent' },
  { id: 'win-x64', pkg: '@auto-ai/agent-win-x64', bin: 'agent.exe' },
]

function resolvePlatformPackage() {
  const { platform, arch } = process
  if (platform === 'linux' && arch === 'x64') {
    return PLATFORM_PACKAGES.find(p => p.id === 'linux-x64')
  }
  if (platform === 'linux' && arch === 'arm64') {
    return PLATFORM_PACKAGES.find(p => p.id === 'linux-arm64')
  }
  if (platform === 'darwin' && arch === 'x64') {
    return PLATFORM_PACKAGES.find(p => p.id === 'darwin-x64')
  }
  if (platform === 'darwin' && arch === 'arm64') {
    return PLATFORM_PACKAGES.find(p => p.id === 'darwin-arm64')
  }
  if (platform === 'win32' && arch === 'x64') {
    return PLATFORM_PACKAGES.find(p => p.id === 'win-x64')
  }
  return null
}

const spec = resolvePlatformPackage()
if (!spec) {
  const supported = PLATFORM_PACKAGES.map(p => p.id).join(', ')
  console.error(
    `agent: 不支持的平台 ${process.platform}/${process.arch}。\n` +
      `支持: ${supported}\n` +
      `请确认已安装 @auto-ai/agent 且 optional 平台包可用。`,
  )
  process.exit(1)
}

const require = createRequire(import.meta.url)
let binPath
try {
  binPath = require.resolve(`${spec.pkg}/${spec.bin}`)
} catch (err) {
  console.error(
    `agent: 未找到平台包 ${spec.pkg}（${spec.id}）。\n` +
      `请重新安装: npm install -g @auto-ai/agent\n` +
      `原始错误: ${err instanceof Error ? err.message : String(err)}`,
  )
  process.exit(1)
}

const result = spawnSync(binPath, process.argv.slice(2), {
  stdio: 'inherit',
  env: buildLauncherEnv(),
})

if (result.error) {
  console.error(`agent: 启动失败: ${result.error.message}`)
  process.exit(1)
}

process.exit(result.status ?? 1)
