import config from 'config'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { isO11yTestHostEnabled } from 'dbaas/utils/feature-flags'

// get metrics from new o11y data source
// ref doc: https://pingcap.feishu.cn/wiki/wikcnylsCKwfSPb4g3QcoTACWId
export const getMetricsBaseUrl = (tenantID: string, projectID: string, cluster: SharedCluster | null): string => {
  if (!cluster) {
    return ''
  }

  const {
    id: clusterID,
    provider,
    region,
    computed: { isServerless }
  } = cluster

  const releaseEnv = config.RELEASE_ENV
  let bizType = ''
  if (isServerless) {
    bizType = `${releaseEnv}-devtier`
  } else if (releaseEnv === 'dev' || releaseEnv === 'staging') {
    bizType = `${releaseEnv}-tidbcloud`
  } else if (releaseEnv === 'prod') {
    bizType = 'tidbcloud'
  }

  let domainSuffix = 'observability.tidbcloud.com'
  if (isO11yTestHostEnabled(tenantID, projectID)) {
    domainSuffix = config.O11Y_TEST_HOST_DOMAIN_SUFFIX || 'observability.tidbcloud.com'
  }

  if (bizType !== '' && tenantID !== '' && projectID !== '') {
    const dsRegionalDomain = `https://www.ds.${region}.${provider}.${domainSuffix}`
    const applicationID = clusterID
    return `${dsRegionalDomain}/external/metrics/${bizType}/tenant/${tenantID}/project/${projectID}/application/${applicationID}`
  }

  return ''
}

export const humanByteSize = (bytes: number, si = false, precision = 1) => {
  const thresh = si ? 1000 : 1024
  if (Math.abs(bytes) < thresh) {
    return bytes + ' B'
  }
  const units = si
    ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
  let u = -1
  do {
    bytes /= thresh
    ++u
  } while (Math.abs(bytes) >= thresh && u < units.length - 1)
  return bytes.toFixed(precision) + ' ' + units[u]
}
