#!/usr/bin/env node
import { spawnSync } from 'node:child_process'

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

const AUTO_ORDER = ['codex', 'qoder', 'claude-code', 'codebuddy', 'trae']

function commandExists(command) {
  const result = spawnSync(command, ['--version'], {
    stdio: 'ignore',
    shell: process.platform === 'win32',
  })
  return result.status === 0
}

function runNpmScript(script, args = []) {
  const result = spawnSync('npm', ['run', script, ...args], {
    stdio: 'inherit',
    shell: process.platform === 'win32',
  })
  if (result.status !== 0) process.exit(result.status || 1)
}

export function chooseRuntimePreset(hasCommand = commandExists) {
  const presets = new Map(listRuntimePresets().map(p => [p.code, p]))
  for (const code of AUTO_ORDER) {
    const preset = presets.get(code)
    if (preset?.command && hasCommand(preset.command)) return preset
  }
  return null
}

if (process.argv[1] && process.argv[1].endsWith('aipros-auto-start.mjs')) {
  console.log('AIPROS Lite 一键启动')
  console.log('先自动选择本机 AI CLI，再启动本地服务。\n')

  const preset = chooseRuntimePreset()
  if (preset) {
    console.log(`✓ 检测到 ${preset.name}，自动配置 Skill 生成、评测、运行的本地运行时。`)
    runNpmScript('runtime:setup', ['--', preset.code])
  } else {
    console.log('! 未检测到 Codex / Qoder / Claude Code / CodeBuddy / Trae。')
    console.log('  平台仍会启动；Skill 生成、评测、运行需要稍后在“智能体配置 / 运行时注册”里配置本地 AI CLI。')
    console.log('  也可以安装并登录 Codex CLI 后重新运行：npm start\n')
  }

  runNpmScript('local')
}
