export type DimsdkProviderAdapter
  = 'openai'
    | 'openai-responses'
    | 'gemini'
    | 'anthropic'

export type ProviderEnvInspection = Readonly<{
  explicitAdapter: DimsdkProviderAdapter | ''
  hasAnthropicKey: boolean
  hasGeminiKey: boolean
  hasOpenAiKey: boolean
  keyCount: number
}>

function normalizeText(value: unknown): string {
  return String(value ?? '').trim()
}

export function inspectProviderEnv(
  env: Record<string, string | undefined> | undefined,
): ProviderEnvInspection {
  const source = env ?? {}
  const explicit = normalizeText(source.DIMCODE_PROVIDER_ADAPTER).toLowerCase()
  const explicitAdapter
    = explicit === 'openai'
      || explicit === 'openai-responses'
      || explicit === 'gemini'
      || explicit === 'anthropic'
      ? explicit
      : ''
  const hasOpenAiKey = Boolean(normalizeText(source.OPENAI_API_KEY))
  const hasGeminiKey = Boolean(normalizeText(source.GOOGLE_API_KEY))
  const hasAnthropicKey = Boolean(normalizeText(source.ANTHROPIC_API_KEY))
  const keyCount
    = Number(hasOpenAiKey) + Number(hasGeminiKey) + Number(hasAnthropicKey)

  return {
    explicitAdapter,
    hasAnthropicKey,
    hasGeminiKey,
    hasOpenAiKey,
    keyCount,
  }
}

export function resolveRuntimeAdapter(
  inspection: ProviderEnvInspection,
): DimsdkProviderAdapter {
  if (inspection.explicitAdapter)
    return inspection.explicitAdapter
  if (inspection.hasAnthropicKey && !inspection.hasOpenAiKey && !inspection.hasGeminiKey)
    return 'anthropic'
  if (inspection.hasGeminiKey && !inspection.hasOpenAiKey && !inspection.hasAnthropicKey)
    return 'gemini'
  return 'openai'
}

export function readProviderApiKeyForAdapter(
  env: Record<string, string | undefined> | undefined,
  adapter: DimsdkProviderAdapter,
): string {
  const source = env ?? {}
  if (adapter === 'gemini')
    return normalizeText(source.GOOGLE_API_KEY)
  if (adapter === 'anthropic')
    return normalizeText(source.ANTHROPIC_API_KEY)
  return normalizeText(source.OPENAI_API_KEY)
}

export function readProviderBaseUrlForAdapter(
  env: Record<string, string | undefined> | undefined,
  adapter: DimsdkProviderAdapter,
): string {
  const source = env ?? {}
  if (adapter === 'gemini')
    return normalizeText(source.DIMCODE_GEMINI_BASE_URL)
  if (adapter === 'anthropic')
    return normalizeText(source.DIMCODE_ANTHROPIC_BASE_URL)
  return normalizeText(source.DIMCODE_OPENAI_BASE_URL ?? source.OPENAI_BASE_URL)
}
