import type { ProviderAdapter } from '#cli/compat/providers'

function isHttpProtocol(protocol: string): boolean {
  return protocol === 'http:' || protocol === 'https:'
}

function normalizeOpenAiCompatibleBaseUrl(input: string): string {
  const raw = String(input ?? '').trim()
  if (!raw) return ''

  try {
    const url = new URL(raw)
    if (!isHttpProtocol(url.protocol)) return raw

    // Users often paste full endpoint URLs; keep only the API root.
    const originalPath = String(url.pathname ?? '')
    let path = originalPath.replace(
      /\/(?:chat\/completions|responses)\/?$/,
      '/',
    )
    if (path.length > 1) path = path.replace(/\/+$/, '')
    if (path === originalPath) return raw
    url.pathname = path
    return url.toString()
  } catch {
    return raw
  }
}

export function normalizeProviderBaseUrl(
  adapter: ProviderAdapter,
  input: string,
): string {
  const raw = String(input ?? '').trim()
  if (!raw) return ''
  if (adapter === 'openai' || adapter === 'openai-responses')
    return normalizeOpenAiCompatibleBaseUrl(raw)
  return raw
}

export function isValidProviderBaseUrl(input: string): boolean {
  const raw = String(input ?? '').trim()
  if (!raw) return false
  try {
    const url = new URL(raw)
    return isHttpProtocol(url.protocol)
  } catch {
    return false
  }
}
