/**
 * H5 读路径消息 content 精简：只保留前端实际渲染的块。
 *
 * 展示层（h5-message-render）仅消费：
 *   - text
 *   - image_attachment / file_attachment
 * 并明确忽略 tool_use / tool_result / thinking / agent_content 等。
 *
 * 本函数只用于 API 出站映射，**绝不写库**——DB 仍保留完整 blocks，
 * 供引擎 resume、owner 桌面端、导出等路径使用。
 */

/** H5 展示所需的 ContentBlock type 白名单（顺序与前端抽取一致）。 */
const H5_DISPLAY_BLOCK_TYPES = new Set([
  'text',
  'image_attachment',
  'file_attachment',
])

/**
 * 将 messages.content 精简为 H5 可展示的 JSON 字符串。
 *
 * - 能 parse 为数组：过滤后 JSON.stringify（保持原相对顺序）
 * - 非数组 / 解析失败：原样返回（兼容纯文本历史数据）
 */
export function stripH5MessageContent(content: string): string {
  if (!content) return content
  try {
    const parsed: unknown = JSON.parse(content)
    if (!Array.isArray(parsed)) return content

    const kept = parsed.filter((block) => {
      if (!block || typeof block !== 'object') return false
      const type = (block as { type?: unknown }).type
      return typeof type === 'string' && H5_DISPLAY_BLOCK_TYPES.has(type)
    })

    // 无变化时尽量返回原串，避免无意义的 re-serialize 差异
    if (kept.length === parsed.length) return content
    return JSON.stringify(kept)
  } catch {
    return content
  }
}

/** 对消息列表批量 strip content（读路径出站用）。 */
export function mapMessagesForH5Response<T extends { content: string }>(
  messages: T[],
): T[] {
  return messages.map((m) => ({
    ...m,
    content: stripH5MessageContent(m.content),
  }))
}
