import { isLocal } from './utils'

const globalWindow = window as Window & {
  getWebAppBackendUrl?: (path: string) => string
}

const globalParent = window.parent as Window & {
  getWebAppBackendUrl?: (path: string) => string
}

/**
 * Get the backend URL based on the current environment.
 * In DSS mode, uses the getWebAppBackendUrl function.
 * In local dev mode, uses the configured API port.
 */
export function getBackendUrl(): string {
  // Try to get backend URL from DSS (iframe or direct)
  const getWebappBackendUrlFn = globalWindow.getWebAppBackendUrl || globalParent.getWebAppBackendUrl

  let backendUrl: string | null = null

  if (typeof getWebappBackendUrlFn === 'function') {
    backendUrl = getWebappBackendUrlFn('')
  }

  // If we have a DSS backend URL, return it (strip trailing slash to avoid //api)
  if (backendUrl) {
    return backendUrl.endsWith('/') ? backendUrl.slice(0, -1) : backendUrl
  }

  // Local development mode
  if (isLocal()) {
    const apiPort = import.meta.env.VITE_API_PORT || '5000'
    return `http://127.0.0.1:${apiPort}`
  }

  // Fallback to base URL (strip trailing slash to avoid //api)
  const baseUrl = import.meta.env.BASE_URL || ''
  return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
}
