/**
 * WeCom template card extractor — 从 bridge-manager 迁入（C-2.1）。
 * 从文本的 JSON 代码块中提取企微模板卡片（card_type + task_id），
 * 供 WecomStreamRenderer 与 bridge.deliverPlatformFinal 复用。
 */

/**
 * Extract WeCom template cards from JSON code blocks.
 * Returns the extracted cards and the text with card blocks removed.
 */
export function extractTemplateCards(text: string): { cards: Record<string, unknown>[]; remainingText: string } {
  // Fast path: short-circuit when the text has no card-like JSON.
  if (!text.includes('```json') || !text.includes('card_type')) {
    return { cards: [], remainingText: text }
  }
  const cards: Record<string, unknown>[] = []
  const remainingText = text.replace(/```json\s*([\s\S]*?)\s*```/g, (block, body) => {
    try {
      const json = JSON.parse(body) as unknown
      if (json && typeof json === 'object' && 'card_type' in json && 'task_id' in json) {
        cards.push(json as Record<string, unknown>)
        return ''
      }
    } catch {
      // Not a card — leave the block in the text.
    }
    return block
  }).replace(/\n{3,}/g, '\n\n').trim()
  return { cards, remainingText }
}
