import type { AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS } from '../../services/analytics/index.js'
import { isEnvTruthy } from '../envUtils.js'

export type APIProvider = 'firstParty' | 'bedrock' | 'vertex' | 'foundry'

export function getAPIProvider(): APIProvider {
  return isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK)
    ? 'bedrock'
    : isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX)
      ? 'vertex'
      : isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)
        ? 'foundry'
        : 'firstParty'
}

export function getAPIProviderForStatsig(): AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS {
  return getAPIProvider() as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
}

/**
 * Check if ANTHROPIC_BASE_URL is a first-party Anthropic API URL.
 * Returns true if not set (default API) or points to api.anthropic.com
 * (or api-staging.anthropic.com for ant users).
 */
export function isFirstPartyAnthropicBaseUrl(): boolean {
  const baseUrl = process.env.ANTHROPIC_BASE_URL
  if (!baseUrl) {
    return true
  }
  try {
    const host = new URL(baseUrl).host
    const allowedHosts = ['api.anthropic.com']
    if (process.env.USER_TYPE === 'ant') {
      allowedHosts.push('api-staging.anthropic.com')
    }
    return allowedHosts.includes(host)
  } catch {
    return false
  }
}

/**
 * RiOS Anthropic-compatible gateway (preload maps RIOS_BASE_URL → ANTHROPIC_BASE_URL).
 * Used to treat OAuth + cloud API features as eligible when the inference host is RiOS,
 * not only api.anthropic.com.
 */
export function isRiOsGatewayAnthropicBaseUrl(): boolean {
  const baseUrl = process.env.ANTHROPIC_BASE_URL
  if (!baseUrl) {
    return false
  }
  try {
    const hostname = new URL(baseUrl).hostname.toLowerCase()
    if (hostname === 'mlm.rios.com.ai') {
      return true
    }
    return hostname.endsWith('.rios.com.ai')
  } catch {
    return false
  }
}

/**
 * API 请求应按 RiOS 编排器鉴权（sk_rios_* / RiOS JWT），不要用 Anthropic 订阅 OAuth。
 * 比 {@link isRiOsGatewayAnthropicBaseUrl} 更宽：自建网关域名、仅配 RIOS_* / sk_rios 时也会为 true，
 * 避免订阅用户把 ANTHROPIC_BASE_URL 指到非 *.rios.com.ai 时仍走 Claude OAuth 导致 401。
 */
export function isRiOsInferenceSession(): boolean {
  if (isRiOsGatewayAnthropicBaseUrl()) {
    return true
  }
  if (process.env.RIOS_BASE_URL?.trim()) {
    return true
  }
  const k = process.env.RIOS_API_KEY ?? process.env.ANTHROPIC_API_KEY ?? ''
  if (k.trimStart().startsWith('sk_rios_')) {
    return true
  }
  return false
}

/** Official Anthropic API or RiOS-managed gateway (settings sync, policy limits, etc.). */
export function isFirstPartyOrRiOsGatewayBaseUrl(): boolean {
  return (
    isFirstPartyAnthropicBaseUrl() || isRiOsGatewayAnthropicBaseUrl()
  )
}
