#!/usr/bin/env node
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import {
  buildRuntimePatch,
  getRuntimePreset,
  listRuntimePresets,
} from './runtime-presets.mjs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
const workerEnvPath = path.join(rootDir, 'cf-worker', '.env')

function parseArgs(argv) {
  const out = { _: [] }
  for (let i = 0; i < argv.length; i += 1) {
    const item = argv[i]
    if (!item.startsWith('--')) {
      out._.push(item)
      continue
    }
    const key = item.slice(2)
    const next = argv[i + 1]
    if (next && !next.startsWith('--')) {
      out[key] = next
      i += 1
    } else {
      out[key] = true
    }
  }
  return out
}

function renderHelp() {
  const rows = listRuntimePresets()
    .map(p => `  ${p.code.padEnd(12)} ${p.name}，默认命令：${p.command || '(需 --command)'}`)
    .join('\n')
  return [
    'AIPROS Lite 本地运行时配置',
    '',
    '用法：',
    '  npm run runtime:setup -- codex',
    '  npm run runtime:setup -- qoder --command /usr/local/bin/qoder',
    '  npm run runtime:setup -- custom --command my-ai-cli --args "-"',
    '',
    '可选运行时：',
    rows,
    '',
    '说明：',
    '  该命令会把预设写入 cf-worker/.env 的 AIPROS_LOCAL_RUNTIME_PATCH。',
    '  下次 npm run local 初始化本地服务时，会把配置同步进「智能体配置 / 运行时注册」。',
  ].join('\n')
}

function updateEnvFile(filePath, key, value) {
  const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : ''
  const line = `${key}=${value}`
  const next = existing.match(new RegExp(`^${key}=`, 'm'))
    ? existing.replace(new RegExp(`^${key}=.*$`, 'm'), line)
    : `${existing.replace(/\s*$/, '\n')}${line}\n`
  fs.mkdirSync(path.dirname(filePath), { recursive: true })
  fs.writeFileSync(filePath, next)
}

const args = parseArgs(process.argv.slice(2))
const code = args._[0] || ''
if (!code || args.help) {
  console.log(renderHelp())
  process.exit(code ? 0 : 1)
}

const preset = getRuntimePreset(code)
if (!preset) {
  console.error(`未知运行时：${code}`)
  console.error(renderHelp())
  process.exit(1)
}

const patch = buildRuntimePatch(preset.code, {
  command: args.command || preset.command,
  args: typeof args.args === 'string' ? args.args.split(/\s+/).filter(Boolean) : undefined,
  healthcheckArgs: typeof args.healthcheck === 'string' ? args.healthcheck.split(/\s+/).filter(Boolean) : undefined,
  timeoutMs: args.timeout ? Number(args.timeout) : undefined,
  enabled: args.enable !== false,
})

if (!patch.command) {
  console.error('自定义运行时必须提供 --command。')
  process.exit(1)
}

const payload = {
  runtimeCode: preset.runtimeCode,
  patch,
  installHint: preset.installHint,
  updatedAt: new Date().toISOString(),
}

updateEnvFile(workerEnvPath, 'AIPROS_LOCAL_RUNTIME_PATCH', JSON.stringify(payload))

console.log(`已写入本地运行时配置：${preset.name}`)
console.log(`运行时编号：${preset.runtimeCode}`)
console.log(`命令：${patch.command} ${patch.args.join(' ')}`)
console.log('下一步：运行 npm run local，然后进入「智能体配置 / 运行时注册」测试并选择该运行时。')
