import type { ChatMessage } from "@qjclaw/shared-types"

export function formatSessionTitle(title: string, index: number, defaultChatName = "千匠问天"): string {
  const normalized = title.trim()
  if (!normalized) {
    return `会话记录 ${index + 1}`
  }
  if (/^new session\s*(\d+)$/i.test(normalized)) {
    const matched = /^new session\s*(\d+)$/i.exec(normalized)
    return `会话记录 ${matched?.[1] ?? String(index + 1)}`
  }
  if (/^default session$/i.test(normalized) || normalized === defaultChatName) {
    return "主会话"
  }
  return normalized
}

export function deriveSidebarSessionTitle(messages: ChatMessage[]): string {
  const firstUserMessage = messages.find((message) => message.role === "user" && message.content.trim())
  if (!firstUserMessage) {
    return "待开始对话"
  }

  const normalized = firstUserMessage.content.replace(/\s+/g, " ").trim()
  if (!normalized) {
    return "待开始对话"
  }

  const preview = [...normalized].slice(0, 5).join("")
  return normalized.length > preview.length ? `${preview}...` : preview
}
