import type { JSONContent } from "@tiptap/react"
import type { EditorDoc, EditorQuestion, EditorStructureNode } from "./exam-rich-editor-types"

const textToParagraphs = (text: string): JSONContent[] => {
  const lines = text.split("\n").filter((l) => l.trim().length > 0)
  return lines.map((line) => ({
    type: "paragraph",
    content: [{ type: "text", text: line }],
  }))
}

const questionToBlock = (q: EditorQuestion): JSONContent => {
  const content: JSONContent[] = textToParagraphs(q.content.text)
  if (q.content.options) {
    content.push({
      type: "orderedList",
      content: q.content.options.map((o) => ({
        type: "listItem",
        content: [
          {
            type: "paragraph",
            content: [{ type: "text", text: `${o.id}. ${o.text}` }],
          },
        ],
      })),
    })
  }
  if (q.content.images) {
    for (const img of q.content.images) {
      content.push({
        type: "image",
        attrs: { src: img.url, "data-file-id": img.fileId, alt: img.alt ?? "" },
      })
    }
  }
  return {
    type: "questionBlock",
    attrs: { questionId: q.id, type: q.type, score: q.score },
    content,
  }
}

/**
 * 将试卷结构(EditorDoc)转换为 Tiptap 编辑器文档(JSONContent)。
 * 用于回填已有试卷到编辑器。支持 section/group/question 三层嵌套。
 */
export const structureToEditorDoc = (doc: EditorDoc): JSONContent => {
  const convertNode = (node: EditorStructureNode): JSONContent | null => {
    if (node.type === "section") {
      const children: JSONContent[] = []
      for (const child of node.children ?? []) {
        const block = convertNode(child)
        if (block) children.push(block)
      }
      return {
        type: "sectionBlock",
        attrs: { title: node.title ?? "", level: node.level ?? 1 },
        content: children,
      }
    }
    if (node.type === "group") {
      const children: JSONContent[] = []
      for (const child of node.children ?? []) {
        const block = convertNode(child)
        if (block) children.push(block)
      }
      return {
        type: "groupBlock",
        attrs: { title: node.title ?? "", instruction: node.instruction ?? "" },
        content: children,
      }
    }
    if (node.type === "question") {
      const q = doc.questions.find((x) => x.id === node.questionId)
      if (q) return questionToBlock(q)
    }
    return null
  }

  const content: JSONContent[] = []
  for (const node of doc.structure) {
    const block = convertNode(node)
    if (block) content.push(block)
  }
  return { type: "doc", content }
}
