/**
 * Card decision logic for Feishu messages.
 *
 * Determines whether a text response should be sent as an interactive
 * card (for better rendering of tables, code blocks, etc.) or as
 * plain text.
 *
 * Adapted from openclaw-lark's card/reply-mode.ts.
 */

import { findMarkdownTablesOutsideCodeBlocks } from './card-error'

// Feishu card has a limit on the number of tables per card.
// Exceeding this limit causes the card API to reject the message.
const FEISHU_CARD_TABLE_LIMIT = 5

/**
 * Check if the text contains Markdown elements that benefit from
 * card rendering (tables, code blocks, many links).
 */
export function shouldUseCard(text: string): boolean {
  // Table limit takes priority — too many tables will cause card API rejection
  const tableMatches = findMarkdownTablesOutsideCodeBlocks(text)
  if (tableMatches.length > FEISHU_CARD_TABLE_LIMIT) {
    return false
  }

  // Fenced code blocks
  if (/```[\s\S]*?```/.test(text)) {
    return true
  }

  // Markdown tables found outside code blocks
  if (tableMatches.length > 0) {
    return true
  }

  return false
}