/**
 * Build WebSocket URLs consistent with HTTP API base (VITE_API_BASE or same-origin).
 */
export function buildWebSocketUrl(path: string, query?: Record<string, string>): string {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  const base = (import.meta.env.VITE_API_BASE as string | undefined) || ''

  let origin: string
  if (base.startsWith('http://') || base.startsWith('https://')) {
    origin = base.replace(/^http/, 'ws').replace(/\/api\/?$/, '')
  } else {
    const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    origin = `${proto}//${window.location.host}`
  }

  const url = new URL(normalizedPath, `${origin}/`)
  if (query) {
    for (const [k, v] of Object.entries(query)) {
      if (v !== undefined && v !== '') url.searchParams.set(k, v)
    }
  }
  return url.toString()
}
