import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const scriptDir = dirname(fileURLToPath(import.meta.url))
const packageDir = dirname(scriptDir)
const packageJson = JSON.parse(
  await readFile(join(packageDir, 'package.json'), 'utf8'),
)

const version = packageJson.version
const baseUrl =
  process.env.TURING_DOWNLOAD_BASE_URL ??
  `https://turing.tap365.org/v${version}`

const targets = {
  darwin: {
    x64: {
      remoteName: `turing-v${version}-macos-x64`,
      localName: 'turing',
    },
  },
  linux: {
    x64: {
      remoteName: `turing-v${version}-linux-x64-max`,
      localName: 'turing',
    },
  },
  win32: {
    x64: {
      remoteName: `turing-v${version}-windows-x64.exe`,
      localName: 'turing.exe',
    },
  },
}

const target = targets[process.platform]?.[process.arch]

if (!target) {
  console.error(
    `错误：当前 npm 安装包不支持 ${process.platform}/${process.arch}。`,
  )
  process.exit(1)
}

const vendorDir = join(packageDir, 'vendor')
const localPath = join(vendorDir, target.localName)
const downloadUrl = `${baseUrl}/${target.remoteName}`

await mkdir(vendorDir, { recursive: true })

const response = await fetch(downloadUrl)
if (!response.ok) {
  console.error(`错误：下载二进制失败：${downloadUrl} -> HTTP ${response.status}`)
  process.exit(1)
}

const binary = Buffer.from(await response.arrayBuffer())
await writeFile(localPath, binary)

if (process.platform !== 'win32') {
  await chmod(localPath, 0o755)
}

console.log(`已下载 Turing Code 二进制：${downloadUrl}`)
console.log('已安装命令：turing / turingopenai / turinggemini / turinggrok / turingclaude / turingp')
console.log('当前内测发布默认走内置 provider registry，通常无需手动配置 Base URL。')
console.log('请优先设置环境变量；若需要持久化，可把 key 写入 ~/.claude/settings.json 的 env。')
