import type { Message } from '#cli/core/model'

export function isRenderableChatMessage(
  m: Message | undefined | null,
): boolean {
  return Boolean(m && m.role !== 'tool')
}

export function countRenderableMessages(
  messages: readonly Message[],
  endExclusive?: number,
): number {
  const end =
    typeof endExclusive === 'number'
      ? Math.max(0, Math.min(messages.length, Math.floor(endExclusive)))
      : messages.length
  let n = 0
  for (let i = 0; i < end; i++) {
    if (isRenderableChatMessage(messages[i])) n++
  }
  return n
}

/**
 * Compute the earliest index into `messages` such that the suffix starting at that index
 * contains at most `maxRenderableMessages` renderable messages (role !== 'tool').
 *
 * This is used as a "virtualized window" to avoid rendering extremely long transcripts
 * synchronously. Older messages can be loaded on demand.
 */
export function computeChatRenderWindowStart(
  messages: readonly Message[],
  maxRenderableMessages: number,
): number {
  const limit = Math.max(0, Math.floor(maxRenderableMessages))
  if (!limit) return messages.length

  let seen = 0
  for (let i = messages.length - 1; i >= 0; i--) {
    const m = messages[i]
    if (!isRenderableChatMessage(m)) continue
    seen++
    if (seen >= limit) return i
  }
  return 0
}
