/** Public path for OpenWebUI (default /ai). */
export function resolveAiEmbedBase(publicPath = "/ai"): string {
  const path = (publicPath || "/ai").replace(/\/$/, "") || "/ai"
  const normalized = path.startsWith("/") ? path : `/${path}`
  const origin = process.env.NEXT_PUBLIC_AI_ORIGIN?.trim().replace(/\/$/, "")
  return origin ? `${origin}${normalized}` : normalized
}

export function resolveAiEmbedOrigin(publicPath = "/ai"): string {
  const base = resolveAiEmbedBase(publicPath)
  if (base.startsWith("http://") || base.startsWith("https://")) {
    return new URL(base).origin
  }
  if (typeof window !== "undefined") {
    return window.location.origin
  }
  return ""
}

export function buildAiEmbedUrl(publicPath: string, searchParams: string): string {
  const base = resolveAiEmbedBase(publicPath)
  return searchParams ? `${base}/?${searchParams}` : `${base}/`
}
