import { homedir } from 'node:os'
import { join } from 'node:path'

export const DEFAULT_TURING_GATEWAY_BASE_URL = 'https://api.tap365.org'
export const TURING_DISABLE_GLOBAL_CONFIG_ENV = 'TURING_DISABLE_GLOBAL_CONFIG'
export const DEFAULT_TURING_OPENAI_IMAGE_BASE_URL = 'https://progpt.tap365.org/c2a-4a57f72b'
export const TURING_PROVIDER_DEFAULTS = {
  openai: {
    baseUrl: `${DEFAULT_TURING_GATEWAY_BASE_URL}/v1`,
    model: 'gpt-5.4',
    imageModel: 'gpt-image-1-mini',
  },
  grok: {
    baseUrl: 'https://grok74.tap365.org/v1',
    model: 'grok-4.1-fast',
  },
  google: {
    baseUrl: 'https://google.tap365.org/v1',
    model: 'gemini-3.1-flash-image',
  },
  gemini: {
    baseUrl: `${DEFAULT_TURING_GATEWAY_BASE_URL}/v1`,
    model: 'gemini-3.1-flash-lite-preview',
  },
  claude: {
    baseUrl: DEFAULT_TURING_GATEWAY_BASE_URL,
    model: 'claude-sonnet-4-6',
  },
}
export const DEFAULT_TURING_OPENAI_BASE_URL = TURING_PROVIDER_DEFAULTS.openai.baseUrl
export const DEFAULT_TURING_OPENAI_CHAT_COMPLETIONS_BASE_URL =
  'https://progpt.tap365.org/c2a-4a57f72b/v1'
export const DEFAULT_TURING_OPENAI_IMAGE_MODEL = TURING_PROVIDER_DEFAULTS.openai.imageModel
export const DEFAULT_TURING_GROK_BASE_URL = TURING_PROVIDER_DEFAULTS.grok.baseUrl
export const DEFAULT_TURING_GOOGLE_BASE_URL = TURING_PROVIDER_DEFAULTS.google.baseUrl
export const DEFAULT_TURING_GEMINI_BASE_URL = TURING_PROVIDER_DEFAULTS.gemini.baseUrl
export const DEFAULT_TURING_ANTHROPIC_BASE_URL = TURING_PROVIDER_DEFAULTS.claude.baseUrl
export const DEFAULT_TURING_GROK_MODEL = TURING_PROVIDER_DEFAULTS.grok.model
export const DEFAULT_TURING_GOOGLE_MODEL = TURING_PROVIDER_DEFAULTS.google.model

function trimToUndefined(value) {
  const trimmed = value?.trim()
  return trimmed ? trimmed : undefined
}

function normalizeBaseUrl(value) {
  const trimmed = trimToUndefined(value)
  if (!trimmed) {
    return undefined
  }
  return trimmed.replace(/\/+$/u, '')
}

function getEnvValue(env, keys) {
  for (const key of keys) {
    const value = trimToUndefined(env[key])
    if (value) {
      return value
    }
  }
  return undefined
}

export function getTuringConfigDir(env = process.env) {
  return (
    trimToUndefined(env.TURING_CONFIG_DIR) ||
    join(trimToUndefined(env.HOME) || trimToUndefined(env.USERPROFILE) || homedir(), '.turing')
  )
}

export function getTuringConfigPath(env = process.env) {
  return join(getTuringConfigDir(env), 'config.json')
}

export function readTuringConfig(env = process.env) {
  void env
  // ~/.turing/config.json 已废弃，不再参与默认 provider 解析链路。
  return null
}

function getConfigValue(config, keys) {
  void config
  void keys
  // 旧的 ~/.turing/config.json 已废弃；保留函数签名仅为兼容现有调用点。
  return undefined
}

function isEnvTruthy(value) {
  if (!value) {
    return false
  }
  return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase())
}

export function resolveTuringProviderPreset(env = process.env) {
  const preset = trimToUndefined(env.TURING_PROVIDER_PRESET)
  if (preset) {
    return preset
  }
  if (isEnvTruthy(env.CLAUDE_CODE_USE_GEMINI)) {
    return 'gemini'
  }
  return 'openai'
}

function ensureOpenAIV1BaseUrl(baseUrl) {
  const normalized = normalizeBaseUrl(baseUrl) || DEFAULT_TURING_OPENAI_BASE_URL
  return normalized.endsWith('/v1') ? normalized : `${normalized}/v1`
}

export function resolveGatewayBaseUrl(env = process.env, config = readTuringConfig(env)) {
  return (
    normalizeBaseUrl(getEnvValue(env, ['TURING_BASE_URL'])) ||
    normalizeBaseUrl(getConfigValue(config, ['TURING_BASE_URL'])) ||
    DEFAULT_TURING_GATEWAY_BASE_URL
  )
}

export function resolveOpenAIBaseUrl(env = process.env, config = readTuringConfig(env)) {
  const explicitBaseUrl =
    normalizeBaseUrl(getEnvValue(env, ['OPENAI_BASE_URL'])) ||
    normalizeBaseUrl(getConfigValue(config, ['OPENAI_BASE_URL']))

  if (explicitBaseUrl) {
    return explicitBaseUrl
  }

  return ensureOpenAIV1BaseUrl(resolveGatewayBaseUrl(env, config))
}

export function resolveOpenAIChatCompletionsBaseUrl(
  env = process.env,
  config = readTuringConfig(env),
) {
  const explicitBaseUrl =
    normalizeBaseUrl(
      getEnvValue(env, [
        'TURING_OPENAI_TEXT_BASE_URL',
        'PROGPT_TEXT_URL',
        'OPENAI_BASE_URL',
      ]),
    ) ||
    normalizeBaseUrl(
      getConfigValue(config, [
        'TURING_OPENAI_TEXT_BASE_URL',
        'PROGPT_TEXT_URL',
        'OPENAI_BASE_URL',
        'PROGPT_IMAGE_URL',
      ]),
    )

  if (explicitBaseUrl) {
    return ensureOpenAIV1BaseUrl(explicitBaseUrl)
  }

  return DEFAULT_TURING_OPENAI_CHAT_COMPLETIONS_BASE_URL
}

export function resolveOpenAIImageBaseUrl(env = process.env, config = readTuringConfig(env)) {
  return (
    normalizeBaseUrl(
      getEnvValue(env, ['TURING_IMAGE_BASE_URL', 'PROGPT_IMAGE_URL']),
    ) ||
    normalizeBaseUrl(
      getConfigValue(config, ['TURING_IMAGE_BASE_URL', 'PROGPT_IMAGE_URL']),
    ) ||
    DEFAULT_TURING_OPENAI_IMAGE_BASE_URL
  )
}

export function resolveGeminiBaseUrl(env = process.env, config = readTuringConfig(env)) {
  const explicitBaseUrl =
    normalizeBaseUrl(
      getEnvValue(env, ['GOOGLE_GEMINI_BASE_URL', 'GEMINI_BASE_URL']),
    ) ||
    normalizeBaseUrl(
      getConfigValue(config, ['GOOGLE_GEMINI_BASE_URL', 'GEMINI_BASE_URL']),
    )

  if (explicitBaseUrl) {
    return ensureOpenAIV1BaseUrl(explicitBaseUrl)
  }

  return ensureOpenAIV1BaseUrl(
    resolveGatewayBaseUrl(env, config) || DEFAULT_TURING_GEMINI_BASE_URL,
  )
}

export function resolveGrokBaseUrl(env = process.env, config = readTuringConfig(env)) {
  const explicitBaseUrl =
    normalizeBaseUrl(getEnvValue(env, ['GROK_BASE_URL'])) ||
    normalizeBaseUrl(getConfigValue(config, ['GROK_BASE_URL']))

  if (explicitBaseUrl) {
    return explicitBaseUrl
  }

  return DEFAULT_TURING_GROK_BASE_URL
}

export function resolveGoogleBaseUrl(env = process.env, config = readTuringConfig(env)) {
  const explicitBaseUrl =
    normalizeBaseUrl(
      getEnvValue(env, [
        'GOOGLE_BASE_URL',
        'FLOW2API_BASE_URL',
        'TURING_GOOGLE_BASE_URL',
      ]),
    ) ||
    normalizeBaseUrl(
      getConfigValue(config, [
        'GOOGLE_BASE_URL',
        'FLOW2API_BASE_URL',
        'TURING_GOOGLE_BASE_URL',
      ]),
    )

  if (explicitBaseUrl) {
    return ensureOpenAIV1BaseUrl(explicitBaseUrl)
  }

  return DEFAULT_TURING_GOOGLE_BASE_URL
}

export function resolveAnthropicBaseUrl(env = process.env, config = readTuringConfig(env)) {
  return (
    normalizeBaseUrl(getEnvValue(env, ['ANTHROPIC_BASE_URL'])) ||
    normalizeBaseUrl(getConfigValue(config, ['ANTHROPIC_BASE_URL'])) ||
    resolveGatewayBaseUrl(env, config) ||
    DEFAULT_TURING_ANTHROPIC_BASE_URL
  )
}

export function resolveOpenAIKey(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['OPENAI_API_KEY', 'TURING_KEY']) ||
    getConfigValue(config, ['OPENAI_API_KEY', 'TURING_KEY'])
  )
}

export function resolveOpenAIChatCompletionsKey(
  env = process.env,
  config = readTuringConfig(env),
) {
  return (
    getEnvValue(env, [
      'OPENAI_API_KEY',
      'PROGPT_TEXT_KEY',
      'PROGPT_IMAGE_KEY',
      'TURING_KEY',
    ]) ||
    getConfigValue(config, [
      'OPENAI_API_KEY',
      'PROGPT_TEXT_KEY',
      'PROGPT_IMAGE_KEY',
      'TURING_KEY',
    ])
  )
}

export function resolveOpenAIImageKey(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['TURING_IMAGE_API_KEY', 'PROGPT_IMAGE_KEY', 'OPENAI_API_KEY']) ||
    getConfigValue(config, ['TURING_IMAGE_API_KEY', 'PROGPT_IMAGE_KEY', 'OPENAI_API_KEY'])
  )
}

export function resolveGeminiKey(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['GEMINI_API_KEY', 'GOOGLE_GEMINI_API_KEY', 'TURING_KEY']) ||
    getConfigValue(config, ['GEMINI_API_KEY', 'GOOGLE_GEMINI_API_KEY', 'TURING_KEY'])
  )
}

export function resolveGrokKey(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['GROK_API_KEY', 'OPENAI_API_KEY', 'TURING_KEY']) ||
    getConfigValue(config, ['GROK_API_KEY', 'OPENAI_API_KEY', 'TURING_KEY'])
  )
}

export function resolveGoogleKey(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, [
      'GOOGLE_API_KEY',
      'FLOW2API_API_KEY',
      'TURING_GOOGLE_API_KEY',
      'OPENAI_API_KEY',
      'TURING_KEY',
    ]) ||
    getConfigValue(config, [
      'GOOGLE_API_KEY',
      'FLOW2API_API_KEY',
      'TURING_GOOGLE_API_KEY',
      'OPENAI_API_KEY',
      'TURING_KEY',
    ])
  )
}

export function resolveClaudeGatewayKey(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, [
      'ANTHROPIC_AUTH_TOKEN',
      'ANTHROPIC_API_KEY',
      'OPENAI_API_KEY',
      'TURING_KEY',
    ]) ||
    getConfigValue(config, [
      'ANTHROPIC_AUTH_TOKEN',
      'ANTHROPIC_API_KEY',
      'OPENAI_API_KEY',
      'TURING_KEY',
    ])
  )
}

export function resolveAnthropicKey(env = process.env, config = readTuringConfig(env)) {
  return resolveClaudeGatewayKey(env, config)
}

export function resolveOpenAITransportKey(env = process.env, config = readTuringConfig(env)) {
  const preset = resolveTuringProviderPreset(env)
  if (preset === 'claude') {
    return resolveClaudeGatewayKey(env, config)
  }
  if (preset === 'grok') {
    return resolveGrokKey(env, config)
  }
  if (preset === 'google') {
    return resolveGoogleKey(env, config)
  }
  return resolveOpenAIKey(env, config)
}

export function resolveGeminiModel(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['GEMINI_MODEL', 'GEMINI_DEFAULT_MAIN_MODEL', 'TURING_GEMINI_MODEL']) ||
    getConfigValue(config, ['GEMINI_MODEL', 'GEMINI_DEFAULT_MAIN_MODEL', 'TURING_GEMINI_MODEL']) ||
    TURING_PROVIDER_DEFAULTS.gemini.model
  )
}

export function resolveGrokModel(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['GROK_MODEL', 'TURING_GROK_MODEL']) ||
    getConfigValue(config, ['GROK_MODEL', 'TURING_GROK_MODEL']) ||
    DEFAULT_TURING_GROK_MODEL
  )
}

export function resolveGoogleModel(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['FLOW2API_MODEL', 'TURING_GOOGLE_MODEL']) ||
    getConfigValue(config, ['FLOW2API_MODEL', 'TURING_GOOGLE_MODEL']) ||
    DEFAULT_TURING_GOOGLE_MODEL
  )
}

export function resolveClaudeModel(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['ANTHROPIC_MODEL', 'TURING_CLAUDE_MODEL']) ||
    getConfigValue(config, ['ANTHROPIC_MODEL', 'TURING_CLAUDE_MODEL']) ||
    TURING_PROVIDER_DEFAULTS.claude.model
  )
}

export function resolveOpenAIModel(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['OPENAI_MODEL', 'OPENAI_DEFAULT_MAIN_MODEL', 'TURING_OPENAI_MODEL']) ||
    getConfigValue(config, ['OPENAI_MODEL', 'OPENAI_DEFAULT_MAIN_MODEL', 'TURING_OPENAI_MODEL']) ||
    TURING_PROVIDER_DEFAULTS.openai.model
  )
}

export function resolveOpenAIImageModel(env = process.env, config = readTuringConfig(env)) {
  return (
    getEnvValue(env, ['TURING_IMAGE_MODEL', 'PROGPT_IMAGE_MODEL', 'OPENAI_IMAGE_MODEL']) ||
    getConfigValue(config, ['TURING_IMAGE_MODEL', 'PROGPT_IMAGE_MODEL', 'OPENAI_IMAGE_MODEL']) ||
    DEFAULT_TURING_OPENAI_IMAGE_MODEL
  )
}
