/**
 * 递归统计 Tiptap 节点内的题目数和总分
 *
 * 从 group-block.tsx 和 section-block.tsx 提取的共享纯函数，
 * 消除代码重复并修复 `as never` 类型断言。
 */

/** 可编辑节点的最小结构 */
type EditableNode = {
  type?: string
  attrs?: Record<string, unknown>
  content?: unknown[]
}

/** 类型守卫：判断未知值是否为可编辑节点 */
const isEditableNode = (v: unknown): v is EditableNode =>
  typeof v === "object" && v !== null

/**
 * 递归统计节点内的题目数和总分（含嵌套 section/group/question 的子题）
 *
 * @param node - 包含 content 数组的节点
 * @returns 题目数量和总分
 */
export const countQuestionsAndScore = (
  node: { content?: unknown[] }
): { count: number; score: number } => {
  let count = 0
  let score = 0
  const blocks = node.content ?? []
  for (const raw of blocks) {
    if (!isEditableNode(raw)) continue
    const block: EditableNode = raw
    if (block.type === "questionBlock") {
      const inner = Array.isArray(block.content) ? block.content : []
      const hasSubQuestions = inner.some(
        (n) => isEditableNode(n) && n.type === "questionBlock"
      )
      if (hasSubQuestions) {
        const subStats = countQuestionsAndScore(block)
        count += subStats.count
        score += subStats.score
      } else {
        count += 1
        const s = typeof block.attrs?.score === "number" ? block.attrs.score : 0
        score += s
      }
    } else if (block.type === "sectionBlock" || block.type === "groupBlock") {
      const subStats = countQuestionsAndScore(block)
      count += subStats.count
      score += subStats.score
    }
  }
  return { count, score }
}
