import { t } from '#cli/i18n'
import { sliceByCells, textCellWidth } from '@simon_he/vue-tui'

export function truncateByCellsWithEllipsis(
  text: string,
  maxCells: number,
  ellipsis = '…',
): string {
  const value = String(text ?? '')
  const max = Math.max(0, Math.floor(maxCells ?? 0))
  if (max <= 0) return ''

  if (textCellWidth(value) <= max) return value

  const ellipsisWidth = Math.max(0, textCellWidth(ellipsis))
  if (ellipsisWidth <= 0) return sliceByCells(value, max)

  if (ellipsisWidth >= max) return sliceByCells(ellipsis, max)

  const slice = sliceByCells(value, max - ellipsisWidth)
  return `${slice}${ellipsis}`
}

export function fitModelProviderLabel(
  model: string,
  providerName: string,
  maxCells: number,
): string {
  const safeMax = Math.max(0, Math.floor(maxCells ?? 0))
  if (safeMax <= 0) return ''

  const modelText = String(model ?? '').trim() || t('chatPage.modelFallback')
  const providerText = String(providerName ?? '').trim()

  if (!providerText) return truncateByCellsWithEllipsis(modelText, safeMax)

  const full = `${modelText} ${providerText}`
  if (textCellWidth(full) <= safeMax) return full

  const prefix = `${modelText} `
  const prefixWidth = textCellWidth(prefix)
  if (prefixWidth >= safeMax)
    return truncateByCellsWithEllipsis(modelText, safeMax)

  const providerMax = safeMax - prefixWidth
  const providerFit = truncateByCellsWithEllipsis(providerText, providerMax)
  if (!providerFit) return truncateByCellsWithEllipsis(modelText, safeMax)

  return `${prefix}${providerFit}`
}
