import { spawn } from 'node:child_process'
import { accessSync, constants, readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
  DEFAULT_TURING_ANTHROPIC_BASE_URL,
  DEFAULT_TURING_GEMINI_BASE_URL,
  DEFAULT_TURING_GOOGLE_BASE_URL,
  DEFAULT_TURING_GROK_BASE_URL,
  DEFAULT_TURING_OPENAI_CHAT_COMPLETIONS_BASE_URL,
  DEFAULT_TURING_OPENAI_IMAGE_MODEL,
  DEFAULT_TURING_OPENAI_BASE_URL,
  TURING_DISABLE_GLOBAL_CONFIG_ENV,
  resolveAnthropicKey,
  resolveGeminiKey,
  resolveGoogleBaseUrl,
  resolveGoogleKey,
  resolveGoogleModel,
  resolveGrokBaseUrl,
  resolveGrokKey,
  resolveGrokModel,
  resolveOpenAIChatCompletionsBaseUrl,
  resolveOpenAIChatCompletionsKey,
  resolveOpenAIImageBaseUrl,
  resolveOpenAIImageKey,
  resolveOpenAIImageModel,
  resolveOpenAIModel,
} from './providerConfig.js'

export const TURINGP_ENV_FILE = 'turingp.env'
export const TURINGP_MODEL = 'gemini-3.1-flash-lite-preview'
export const TURINGP_BASE_URL = DEFAULT_TURING_GEMINI_BASE_URL
export const TURING_OPENAI_MODEL = 'gpt-5.4'
export const TURING_OPENAI_BASE_URL = DEFAULT_TURING_OPENAI_CHAT_COMPLETIONS_BASE_URL
export const TURING_OPENAI_TRANSPORT = 'chat_completions'
export const TURING_OPENAI_IMAGE_MODEL = DEFAULT_TURING_OPENAI_IMAGE_MODEL
export const TURING_GOOGLE_MODEL = 'gemini-3.1-flash-image'
export const TURING_GOOGLE_BASE_URL = DEFAULT_TURING_GOOGLE_BASE_URL
export const TURING_GOOGLE_TRANSPORT = 'chat_completions'
export const TURING_GROK_MODEL = 'grok-4.1-fast'
export const TURING_GROK_IMAGE_MODEL = 'grok-imagine-1.0'
export const TURING_GROK_BASE_URL = DEFAULT_TURING_GROK_BASE_URL
export const TURING_GROK_TRANSPORT = 'responses'
export const TURING_CLAUDE_MODEL = 'claude-sonnet-4-6'
export const CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST = 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST'

const PASS_THROUGH_ONLY_FLAGS = new Set(['--help', '-h', '--version', '-v', '-V'])
const SUBCOMMANDS = new Set([
  'agents',
  'auth',
  'doctor',
  'install',
  'mcp',
  'plugin',
  'plugins',
  'setup-token',
  'update',
  'upgrade',
])
const OPTIONS_REQUIRING_VALUE = new Set([
  '--add-dir',
  '--agent',
  '--agents',
  '--allowedTools',
  '--allowed-tools',
  '--append-system-prompt',
  '--betas',
  '-d',
  '--debug',
  '--debug-file',
  '--disallowedTools',
  '--disallowed-tools',
  '--effort',
  '--fallback-model',
  '--file',
  '--from-pr',
  '--input-format',
  '--json-schema',
  '--max-budget-usd',
  '--mcp-config',
  '--model',
  '-m',
  '-n',
  '--name',
  '--output-format',
  '--permission-mode',
  '--plugin-dir',
  '-r',
  '--resume',
  '--session-id',
  '--setting-sources',
  '--settings',
  '--system-prompt',
  '--tmux',
  '--tools',
  '-w',
  '--worktree',
])
const PROVIDER_FLAG_KEYS = new Set([
  'CLAUDE_CODE_USE_BEDROCK',
  'CLAUDE_CODE_USE_VERTEX',
  'CLAUDE_CODE_USE_FOUNDRY',
  'CLAUDE_CODE_USE_GEMINI',
  'CLAUDE_CODE_USE_OPENAI_RESPONSES',
])
const GEMINI_PRESET_KEYS = new Set([
  'CLAUDE_CODE_USE_GEMINI',
  'GEMINI_API_KEY',
  'GOOGLE_GEMINI_API_KEY',
  'GEMINI_BASE_URL',
  'GOOGLE_GEMINI_BASE_URL',
  'GEMINI_MODEL',
  'GEMINI_DEFAULT_MAIN_MODEL',
  'TURING_GEMINI_MODEL',
  'TURING_BASE_URL',
])

export function resolveTuringpEnvPath(baseEnv = process.env) {
  const configDir =
    baseEnv.CLAUDE_CONFIG_DIR || join(homedir(), '.claude').normalize('NFC')
  return join(configDir, TURINGP_ENV_FILE)
}

export function parseSimpleEnvFile(content) {
  const parsedEnv = {}
  const lines = content.split(/\r?\n/)

  for (const rawLine of lines) {
    const line = rawLine.trim()
    if (!line || line.startsWith('#')) {
      continue
    }

    const normalizedLine = line.startsWith('export ')
      ? line.slice('export '.length).trim()
      : line
    const equalIndex = normalizedLine.indexOf('=')
    if (equalIndex <= 0) {
      continue
    }

    const key = normalizedLine.slice(0, equalIndex).trim()
    let value = normalizedLine.slice(equalIndex + 1).trim()

    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1)
    }

    if (!key) {
      continue
    }

    parsedEnv[key] = value
  }

  return parsedEnv
}

export function loadTuringpPresetEnv(baseEnv = process.env) {
  const envFilePath = resolveTuringpEnvPath(baseEnv)

  try {
    const content = readFileSync(envFilePath, 'utf8')
    return parseSimpleEnvFile(content)
  } catch {
    return {}
  }
}

export function resolveBinaryName(platform = process.platform) {
  return platform === 'win32' ? 'turing.exe' : 'turing'
}

export function resolvePackageBinaryPath(metaUrl, platform = process.platform) {
  const binDir = dirname(fileURLToPath(metaUrl))
  const packageDir = dirname(binDir)
  return join(packageDir, 'vendor', resolveBinaryName(platform))
}

function hasSubcommand(argv) {
  const positionalArgs = extractPositionalArgs(argv)
  return positionalArgs.length > 0 ? SUBCOMMANDS.has(positionalArgs[0]) : false
}

function extractPositionalArgs(argv) {
  const positionalArgs = []
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index]
    if (!arg) {
      continue
    }
    if (arg === '--') {
      break
    }
    if (!arg.startsWith('-')) {
      positionalArgs.push(arg)
      continue
    }
    if (OPTIONS_REQUIRING_VALUE.has(arg)) {
      const nextArg = argv[index + 1]
      if (nextArg && !nextArg.startsWith('-')) {
        index += 1
      }
    }
  }
  return positionalArgs
}

function stripModelArgs(argv) {
  const nextArgv = []
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index]
    if (arg === '--model' || arg === '-m') {
      const nextArg = argv[index + 1]
      if (nextArg && !nextArg.startsWith('-')) {
        index += 1
      }
      continue
    }
    if (arg?.startsWith('--model=')) {
      continue
    }
    nextArgv.push(arg)
  }
  return nextArgv
}

function hasExplicitSettingSources(argv) {
  return argv.some(arg => arg === '--setting-sources' || arg?.startsWith('--setting-sources='))
}

function ensureSettingSources(argv, value = 'user') {
  if (hasExplicitSettingSources(argv)) {
    return [...argv]
  }
  return [...argv, '--setting-sources', value]
}

function hasExplicitSettings(argv) {
  return argv.some(arg => arg === '--settings' || arg?.startsWith('--settings='))
}

function hasExplicitModelArg(argv) {
  return argv.some(arg => arg === '--model' || arg === '-m' || arg?.startsWith('--model='))
}

function isImageCommand(argv) {
  return extractPositionalArgs(argv)[0] === 'image'
}

function getImageAction(argv) {
  const positionalArgs = extractPositionalArgs(argv)
  return positionalArgs[0] === 'image' ? positionalArgs[1] : undefined
}

function buildAliasRuntimeEnv(baseEnv) {
  return {
    ...baseEnv,
    [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
  }
}

function hasNonEmptyEnvValue(baseEnv, keys) {
  return keys.some(key => {
    const value = baseEnv[key]
    return typeof value === 'string' ? value.trim().length > 0 : Boolean(value)
  })
}

function shouldApplyMainOpenAIDefaults(baseEnv) {
  const preset = baseEnv.TURING_PROVIDER_PRESET?.trim().toLowerCase()
  if (preset === 'gemini' || preset === 'claude') {
    return false
  }

  if (
    hasNonEmptyEnvValue(baseEnv, [
      'CLAUDE_CODE_USE_BEDROCK',
      'CLAUDE_CODE_USE_VERTEX',
      'CLAUDE_CODE_USE_FOUNDRY',
      'CLAUDE_CODE_USE_GEMINI',
      'GEMINI_BASE_URL',
      'GOOGLE_GEMINI_BASE_URL',
      'GEMINI_API_KEY',
      'GOOGLE_GEMINI_API_KEY',
      'GEMINI_MODEL',
      'GEMINI_DEFAULT_MAIN_MODEL',
      'TURING_GEMINI_MODEL',
    ])
  ) {
    return false
  }

  if (
    hasNonEmptyEnvValue(baseEnv, [
      'ANTHROPIC_BASE_URL',
      'ANTHROPIC_API_KEY',
      'ANTHROPIC_AUTH_TOKEN',
      'ANTHROPIC_MODEL',
    ])
  ) {
    return false
  }

  return true
}

function appendInlineSettings(argv, settings) {
  if (hasExplicitSettings(argv)) {
    return [...argv]
  }
  return [...argv, '--settings', JSON.stringify(settings)]
}

function buildFixedModelArgv(argv, model) {
  if (shouldPassThrough(argv)) {
    return [...argv]
  }
  return ensureSettingSources([
    ...stripModelArgs(argv),
    '--model',
    model,
  ])
}

function shouldPassThrough(argv) {
  return argv.some(arg => PASS_THROUGH_ONLY_FLAGS.has(arg)) || hasSubcommand(argv)
}

function clearKeys(targetEnv, keys) {
  for (const key of keys) {
    delete targetEnv[key]
  }
}

function buildProviderPresetEnv(baseEnv, {
  presetEnv = {},
  providerFlag,
  providerValues = {},
  clearKeys: extraClearKeys = [],
}) {
  const mergedEnv = { ...presetEnv, ...baseEnv }

  clearKeys(mergedEnv, PROVIDER_FLAG_KEYS)
  clearKeys(mergedEnv, extraClearKeys)

  if (providerFlag) {
    mergedEnv[providerFlag] = '1'
  }
  mergedEnv[CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST] = '1'
  Object.assign(mergedEnv, providerValues)

  return mergedEnv
}

function resolvePresetGeminiBaseUrl(baseEnv, presetEnv) {
  const resolvedBaseUrl =
    baseEnv.GEMINI_BASE_URL ||
    baseEnv.GOOGLE_GEMINI_BASE_URL ||
    presetEnv.GEMINI_BASE_URL ||
    presetEnv.GOOGLE_GEMINI_BASE_URL ||
    baseEnv.TURING_BASE_URL ||
    TURINGP_BASE_URL

  return resolvedBaseUrl.endsWith('/v1') || resolvedBaseUrl.endsWith('/v1/')
    ? resolvedBaseUrl
    : `${resolvedBaseUrl.replace(/\/+$/u, '')}/v1`
}

function resolvePresetGeminiModel(baseEnv, presetEnv) {
  return (
    baseEnv.GEMINI_MODEL ||
    baseEnv.GEMINI_DEFAULT_MAIN_MODEL ||
    presetEnv.GEMINI_MODEL ||
    presetEnv.GEMINI_DEFAULT_MAIN_MODEL ||
    presetEnv.TURING_GEMINI_MODEL ||
    TURINGP_MODEL
  )
}

function resolvePresetGeminiKey(baseEnv, presetEnv) {
  return (
    resolveGeminiKey(baseEnv, null) ||
    presetEnv.GEMINI_API_KEY ||
    presetEnv.GOOGLE_GEMINI_API_KEY
  )
}

function buildTuringGeminiImageArgv(
  argv,
  baseEnv = process.env,
  presetEnv = {},
) {
  if (!isImageCommand(argv)) {
    return [...argv]
  }

  if (shouldPassThrough(argv) || hasExplicitModelArg(argv)) {
    return [...argv]
  }

  const imageAction = getImageAction(argv)
  if (
    imageAction !== 'generate' &&
    imageAction !== 'gen' &&
    imageAction !== 'edit' &&
    imageAction !== 'ed'
  ) {
    return [...argv]
  }

  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const geminiModel = resolvePresetGeminiModel(runtimeEnv, presetEnv)
  return [argv[0], imageAction, '--model', geminiModel, ...argv.slice(2)]
}

function resolvePresetAnthropicBaseUrl(baseEnv) {
  return (
    baseEnv.ANTHROPIC_BASE_URL ||
    baseEnv.TURING_BASE_URL ||
    DEFAULT_TURING_ANTHROPIC_BASE_URL
  )
}

export function buildTuringpArgv(
  argv,
  baseEnv = process.env,
  presetEnv = {},
) {
  if (isImageCommand(argv)) {
    return buildTuringGeminiImageArgv(argv, baseEnv, presetEnv)
  }
  if (shouldPassThrough(argv)) {
    return [...argv]
  }
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const geminiModel = resolvePresetGeminiModel(runtimeEnv, presetEnv)
  const nextArgv = buildFixedModelArgv(argv, geminiModel)
  return appendInlineSettings(nextArgv, buildTuringpSettings(baseEnv, presetEnv))
}

export function buildTuringClaudeArgv(argv, baseEnv = process.env) {
  if (isImageCommand(argv)) {
    return [...argv]
  }
  if (shouldPassThrough(argv)) {
    return [...argv]
  }
  const nextArgv = buildFixedModelArgv(argv, TURING_CLAUDE_MODEL)
  return appendInlineSettings(nextArgv, buildTuringClaudeSettings(baseEnv))
}

export function buildTuringpEnv(baseEnv, presetEnv = {}) {
  const sanitizedPresetEnv = { ...presetEnv }
  clearKeys(sanitizedPresetEnv, GEMINI_PRESET_KEYS)
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const geminiApiKey = resolvePresetGeminiKey(runtimeEnv, presetEnv)
  const geminiBaseUrl = resolvePresetGeminiBaseUrl(runtimeEnv, presetEnv)
  const geminiModel = resolvePresetGeminiModel(runtimeEnv, presetEnv)

  return buildProviderPresetEnv(baseEnv, {
    presetEnv: sanitizedPresetEnv,
    providerFlag: 'CLAUDE_CODE_USE_GEMINI',
    providerValues: {
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'gemini',
      GEMINI_MODEL: geminiModel,
      GEMINI_BASE_URL: geminiBaseUrl,
      ...(geminiApiKey
        ? {
            GEMINI_API_KEY: geminiApiKey,
          }
        : {}),
    },
  })
}

export function buildTuringpSettings(
  baseEnv,
  presetEnv = {},
) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const geminiApiKey = resolvePresetGeminiKey(runtimeEnv, presetEnv)
  const geminiBaseUrl = resolvePresetGeminiBaseUrl(runtimeEnv, presetEnv)
  const geminiModel = resolvePresetGeminiModel(runtimeEnv, presetEnv)

  return {
    model: geminiModel,
    env: {
      [CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST]: '1',
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'gemini',
      CLAUDE_CODE_USE_GEMINI: '1',
      CLAUDE_CODE_USE_OPENAI_RESPONSES: '',
      CLAUDE_CODE_USE_BEDROCK: '',
      CLAUDE_CODE_USE_VERTEX: '',
      CLAUDE_CODE_USE_FOUNDRY: '',
      GEMINI_MODEL: geminiModel,
      GEMINI_BASE_URL: geminiBaseUrl,
      ...(geminiApiKey
        ? {
            GEMINI_API_KEY: geminiApiKey,
          }
        : {}),
    },
  }
}

export function buildTuringOpenAISettings(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const openAIBaseUrl =
    resolveOpenAIChatCompletionsBaseUrl(runtimeEnv, null) ||
    DEFAULT_TURING_OPENAI_CHAT_COMPLETIONS_BASE_URL
  const openAIKey = resolveOpenAIChatCompletionsKey(runtimeEnv, null)
  const openAIModel = resolveOpenAIModel(runtimeEnv, null) || TURING_OPENAI_MODEL
  const openAIImageBaseUrl = resolveOpenAIImageBaseUrl(runtimeEnv, null)
  const openAIImageKey = resolveOpenAIImageKey(runtimeEnv, null)
  const openAIImageModel =
    resolveOpenAIImageModel(runtimeEnv, null) || TURING_OPENAI_IMAGE_MODEL

  return {
    model: openAIModel,
    env: {
      [CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST]: '1',
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'openai',
      TURING_OPENAI_TRANSPORT,
      CLAUDE_CODE_USE_GEMINI: '',
      CLAUDE_CODE_USE_OPENAI_RESPONSES: '1',
      CLAUDE_CODE_USE_BEDROCK: '',
      CLAUDE_CODE_USE_VERTEX: '',
      CLAUDE_CODE_USE_FOUNDRY: '',
      GEMINI_BASE_URL: '',
      GEMINI_API_KEY: '',
      GEMINI_MODEL: '',
      GOOGLE_GEMINI_BASE_URL: '',
      GOOGLE_GEMINI_API_KEY: '',
      ANTHROPIC_BASE_URL: '',
      ANTHROPIC_API_KEY: '',
      ANTHROPIC_AUTH_TOKEN: '',
      ANTHROPIC_MODEL: '',
      OPENAI_BASE_URL: openAIBaseUrl,
      OPENAI_MODEL: openAIModel,
      TURING_IMAGE_BASE_URL: openAIImageBaseUrl,
      TURING_IMAGE_MODEL: openAIImageModel,
      ...(openAIKey
        ? {
            OPENAI_API_KEY: openAIKey,
          }
        : {}),
      ...(openAIImageKey
        ? {
            TURING_IMAGE_API_KEY: openAIImageKey,
          }
        : {}),
    },
  }
}

function buildTuringOpenAIImageArgv(argv) {
  return [...argv]
}

export function buildTuringOpenAIArgv(argv, baseEnv = process.env) {
  if (isImageCommand(argv)) {
    return buildTuringOpenAIImageArgv(argv)
  }
  if (shouldPassThrough(argv)) {
    return [...argv]
  }
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const openAIModel = resolveOpenAIModel(runtimeEnv, null) || TURING_OPENAI_MODEL
  const nextArgv = buildFixedModelArgv(argv, openAIModel)
  return appendInlineSettings(nextArgv, buildTuringOpenAISettings(baseEnv))
}

export function buildTuringOpenAIEnv(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const openAIBaseUrl =
    resolveOpenAIChatCompletionsBaseUrl(runtimeEnv, null) ||
    DEFAULT_TURING_OPENAI_CHAT_COMPLETIONS_BASE_URL
  const openAIKey = resolveOpenAIChatCompletionsKey(runtimeEnv, null)
  const openAIModel = resolveOpenAIModel(runtimeEnv, null) || TURING_OPENAI_MODEL
  const openAIImageBaseUrl = resolveOpenAIImageBaseUrl(runtimeEnv, null)
  const openAIImageKey = resolveOpenAIImageKey(runtimeEnv, null)
  const openAIImageModel =
    resolveOpenAIImageModel(runtimeEnv, null) || TURING_OPENAI_IMAGE_MODEL

  return buildProviderPresetEnv(baseEnv, {
    providerFlag: 'CLAUDE_CODE_USE_OPENAI_RESPONSES',
    providerValues: {
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'openai',
      TURING_OPENAI_TRANSPORT,
      OPENAI_BASE_URL: openAIBaseUrl,
      OPENAI_MODEL: openAIModel,
      TURING_IMAGE_BASE_URL: openAIImageBaseUrl,
      TURING_IMAGE_MODEL: openAIImageModel,
      ...(openAIKey
        ? {
            OPENAI_API_KEY: openAIKey,
          }
        : {}),
      ...(openAIImageKey
        ? {
            TURING_IMAGE_API_KEY: openAIImageKey,
          }
        : {}),
    },
    clearKeys: ['GEMINI_MODEL'],
  })
}

function buildTuringGoogleImageArgv(argv) {
  return [...argv]
}

export function buildTuringGoogleArgv(argv, baseEnv = process.env) {
  if (isImageCommand(argv)) {
    return buildTuringGoogleImageArgv(argv)
  }
  if (shouldPassThrough(argv)) {
    return [...argv]
  }
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const googleModel = resolveGoogleModel(runtimeEnv, null) || TURING_GOOGLE_MODEL
  const nextArgv = buildFixedModelArgv(argv, googleModel)
  return appendInlineSettings(nextArgv, buildTuringGoogleSettings(baseEnv))
}

export function buildTuringGoogleEnv(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const googleBaseUrl =
    resolveGoogleBaseUrl(runtimeEnv, null) || TURING_GOOGLE_BASE_URL
  const googleKey = resolveGoogleKey(runtimeEnv, null)
  const googleModel = resolveGoogleModel(runtimeEnv, null) || TURING_GOOGLE_MODEL

  return buildProviderPresetEnv(baseEnv, {
    providerFlag: 'CLAUDE_CODE_USE_OPENAI_RESPONSES',
    providerValues: {
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'google',
      TURING_OPENAI_TRANSPORT: TURING_GOOGLE_TRANSPORT,
      GOOGLE_BASE_URL: googleBaseUrl,
      OPENAI_BASE_URL: googleBaseUrl,
      OPENAI_MODEL: googleModel,
      ...(googleKey
        ? {
            GOOGLE_API_KEY: googleKey,
            FLOW2API_API_KEY: googleKey,
            OPENAI_API_KEY: googleKey,
          }
        : {}),
    },
    clearKeys: ['GEMINI_MODEL'],
  })
}

export function buildTuringGoogleSettings(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const googleBaseUrl =
    resolveGoogleBaseUrl(runtimeEnv, null) || TURING_GOOGLE_BASE_URL
  const googleKey = resolveGoogleKey(runtimeEnv, null)
  const googleModel = resolveGoogleModel(runtimeEnv, null) || TURING_GOOGLE_MODEL

  return {
    model: googleModel,
    env: {
      [CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST]: '1',
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'google',
      TURING_OPENAI_TRANSPORT: TURING_GOOGLE_TRANSPORT,
      CLAUDE_CODE_USE_GEMINI: '',
      CLAUDE_CODE_USE_OPENAI_RESPONSES: '1',
      CLAUDE_CODE_USE_BEDROCK: '',
      CLAUDE_CODE_USE_VERTEX: '',
      CLAUDE_CODE_USE_FOUNDRY: '',
      GEMINI_BASE_URL: '',
      GEMINI_API_KEY: '',
      GEMINI_MODEL: '',
      GOOGLE_GEMINI_BASE_URL: '',
      GOOGLE_GEMINI_API_KEY: '',
      ANTHROPIC_BASE_URL: '',
      ANTHROPIC_API_KEY: '',
      ANTHROPIC_AUTH_TOKEN: '',
      ANTHROPIC_MODEL: '',
      GOOGLE_BASE_URL: googleBaseUrl,
      OPENAI_BASE_URL: googleBaseUrl,
      OPENAI_MODEL: googleModel,
      ...(googleKey
        ? {
            GOOGLE_API_KEY: googleKey,
            FLOW2API_API_KEY: googleKey,
            OPENAI_API_KEY: googleKey,
          }
        : {}),
    },
  }
}

export function buildTuringMainEnv(baseEnv) {
  const nextEnv = {
    ...baseEnv,
    [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
  }

  if (!shouldApplyMainOpenAIDefaults(baseEnv)) {
    return nextEnv
  }

  return {
    ...nextEnv,
    TURING_PROVIDER_PRESET: nextEnv.TURING_PROVIDER_PRESET || 'openai',
    TURING_OPENAI_TRANSPORT: nextEnv.TURING_OPENAI_TRANSPORT || 'responses',
    CLAUDE_CODE_USE_OPENAI_RESPONSES:
      nextEnv.CLAUDE_CODE_USE_OPENAI_RESPONSES || '1',
    OPENAI_BASE_URL: nextEnv.OPENAI_BASE_URL || DEFAULT_TURING_OPENAI_BASE_URL,
    OPENAI_MODEL: nextEnv.OPENAI_MODEL || TURING_OPENAI_MODEL,
  }
}

export function buildTuringClaudeEnv(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const anthropicKey = resolveAnthropicKey(runtimeEnv, null)
  const anthropicBaseUrl = resolvePresetAnthropicBaseUrl(runtimeEnv)

  return buildProviderPresetEnv(baseEnv, {
    providerValues: {
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'claude',
      ANTHROPIC_BASE_URL: anthropicBaseUrl,
      ANTHROPIC_MODEL: TURING_CLAUDE_MODEL,
      ...(anthropicKey
        ? {
            ANTHROPIC_API_KEY: anthropicKey,
            ANTHROPIC_AUTH_TOKEN: anthropicKey,
          }
        : {}),
    },
    clearKeys: [
      'GEMINI_MODEL',
      'GEMINI_BASE_URL',
      'GEMINI_API_KEY',
      'GOOGLE_GEMINI_BASE_URL',
      'GOOGLE_GEMINI_API_KEY',
      'OPENAI_BASE_URL',
      'OPENAI_API_KEY',
      'OPENAI_MODEL',
    ],
  })
}

function buildTuringGrokImageArgv(argv) {
  return [...argv]
}

export function buildTuringGrokEnv(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const grokBaseUrl = resolveGrokBaseUrl(runtimeEnv, null) || TURING_GROK_BASE_URL
  const grokKey = resolveGrokKey(runtimeEnv, null)
  const grokModel = resolveGrokModel(runtimeEnv, null) || TURING_GROK_MODEL

  return buildProviderPresetEnv(baseEnv, {
    providerFlag: 'CLAUDE_CODE_USE_OPENAI_RESPONSES',
    providerValues: {
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'grok',
      TURING_OPENAI_TRANSPORT: TURING_GROK_TRANSPORT,
      OPENAI_BASE_URL: grokBaseUrl,
      OPENAI_MODEL: grokModel,
      TURING_IMAGE_BASE_URL: grokBaseUrl,
      TURING_IMAGE_MODEL: TURING_GROK_IMAGE_MODEL,
      ...(grokKey
        ? {
            GROK_API_KEY: grokKey,
            OPENAI_API_KEY: grokKey,
            TURING_IMAGE_API_KEY: grokKey,
          }
        : {}),
    },
    clearKeys: ['GEMINI_MODEL'],
  })
}

export function buildTuringGrokSettings(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const grokBaseUrl = resolveGrokBaseUrl(runtimeEnv, null) || TURING_GROK_BASE_URL
  const grokKey = resolveGrokKey(runtimeEnv, null)
  const grokModel = resolveGrokModel(runtimeEnv, null) || TURING_GROK_MODEL

  return {
    model: grokModel,
    env: {
      [CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST]: '1',
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'grok',
      TURING_OPENAI_TRANSPORT: TURING_GROK_TRANSPORT,
      CLAUDE_CODE_USE_GEMINI: '',
      CLAUDE_CODE_USE_OPENAI_RESPONSES: '1',
      CLAUDE_CODE_USE_BEDROCK: '',
      CLAUDE_CODE_USE_VERTEX: '',
      CLAUDE_CODE_USE_FOUNDRY: '',
      GEMINI_BASE_URL: '',
      GEMINI_API_KEY: '',
      GEMINI_MODEL: '',
      GOOGLE_GEMINI_BASE_URL: '',
      GOOGLE_GEMINI_API_KEY: '',
      ANTHROPIC_BASE_URL: '',
      ANTHROPIC_API_KEY: '',
      ANTHROPIC_AUTH_TOKEN: '',
      ANTHROPIC_MODEL: '',
      OPENAI_BASE_URL: grokBaseUrl,
      OPENAI_MODEL: grokModel,
      TURING_IMAGE_BASE_URL: grokBaseUrl,
      TURING_IMAGE_MODEL: TURING_GROK_IMAGE_MODEL,
      ...(grokKey
        ? {
            GROK_API_KEY: grokKey,
            OPENAI_API_KEY: grokKey,
            TURING_IMAGE_API_KEY: grokKey,
          }
        : {}),
    },
  }
}

export function buildTuringGrokArgv(argv, baseEnv = process.env) {
  if (isImageCommand(argv)) {
    return buildTuringGrokImageArgv(argv)
  }
  if (shouldPassThrough(argv)) {
    return [...argv]
  }
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const grokModel = resolveGrokModel(runtimeEnv, null) || TURING_GROK_MODEL
  const nextArgv = buildFixedModelArgv(argv, grokModel)
  return appendInlineSettings(nextArgv, buildTuringGrokSettings(baseEnv))
}

export function buildTuringClaudeSettings(baseEnv) {
  const runtimeEnv = buildAliasRuntimeEnv(baseEnv)
  const anthropicKey = resolveAnthropicKey(runtimeEnv, null)
  const anthropicBaseUrl = resolvePresetAnthropicBaseUrl(runtimeEnv)

  return {
    model: TURING_CLAUDE_MODEL,
    env: {
      [CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST]: '1',
      [TURING_DISABLE_GLOBAL_CONFIG_ENV]: '1',
      TURING_PROVIDER_PRESET: 'claude',
      CLAUDE_CODE_USE_GEMINI: '',
      CLAUDE_CODE_USE_OPENAI_RESPONSES: '',
      CLAUDE_CODE_USE_BEDROCK: '',
      CLAUDE_CODE_USE_VERTEX: '',
      CLAUDE_CODE_USE_FOUNDRY: '',
      OPENAI_BASE_URL: '',
      OPENAI_API_KEY: '',
      OPENAI_MODEL: '',
      GEMINI_BASE_URL: '',
      GEMINI_API_KEY: '',
      GEMINI_MODEL: '',
      GOOGLE_GEMINI_BASE_URL: '',
      GOOGLE_GEMINI_API_KEY: '',
      ANTHROPIC_BASE_URL: anthropicBaseUrl,
      ANTHROPIC_MODEL: TURING_CLAUDE_MODEL,
      ...(anthropicKey
        ? {
            ANTHROPIC_API_KEY: anthropicKey,
            ANTHROPIC_AUTH_TOKEN: anthropicKey,
          }
        : {}),
    },
  }
}

export function launchBinaryPath({
  binaryPath,
  argv,
  env = process.env,
  missingBinaryMessage,
}) {
  try {
    accessSync(binaryPath, constants.F_OK)
  } catch {
    console.error(missingBinaryMessage)
    process.exit(1)
  }

  const child = spawn(binaryPath, argv, {
    env,
    stdio: 'inherit',
  })

  child.on('exit', code => {
    process.exit(code ?? 1)
  })

  child.on('error', error => {
    console.error(
      `错误：启动 Turing Code 失败：${error instanceof Error ? error.message : String(error)}`,
    )
    process.exit(1)
  })
}
