import { spawnSync } from 'node:child_process'
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 })

function downloadWithCurl(url, outFile) {
  const result = spawnSync(
    'curl',
    ['-fL', '--retry', '3', '--connect-timeout', '15', '-o', outFile, url],
    {
      stdio: 'ignore',
    },
  )
  return result.status === 0
}

async function downloadWithFetch(url) {
  const response = await fetch(url, {
    signal: AbortSignal.timeout(180_000),
  })
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`)
  }
  return Buffer.from(await response.arrayBuffer())
}

let downloadedByCurl = false
try {
  downloadedByCurl = downloadWithCurl(downloadUrl, localPath)
} catch {
  downloadedByCurl = false
}

if (!downloadedByCurl) {
  try {
    const binary = await downloadWithFetch(downloadUrl)
    await writeFile(localPath, binary)
  } catch (error) {
    console.error(
      `错误：下载二进制失败：${downloadUrl} -> ${error instanceof Error ? error.message : String(error)}`,
    )
    process.exit(1)
  }
}

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

console.log(`已下载 Turing Code 二进制：${downloadUrl}`)
console.log('已安装命令：turing')
console.log(`如需生成 turingopenai / turinggoogle / turinggrok，请执行：curl -fsSL https://turing.tap365.org/v${version}/setup-provider-wrappers.sh | bash`)
console.log('当前 turing 主入口已改为 env-driven；不会再自动注入 provider。')
console.log('请优先设置环境变量；若需要持久化，可把 provider 相关 env 写入 ~/.claude/settings.json。')
