import { createId } from "@paralleldrive/cuid2"
import type { ExamNode } from "../components/assembly/selected-question-list"
import type { Question } from "@/modules/questions/types"
import type {
  EditorDoc,
  EditorQuestion,
  EditorStructureNode,
} from "./exam-rich-editor-types"
import { toRichQuestionType } from "./exam-rich-editor-types"

/**
 * 将 BuildExam 页面的 ExamNode[] + Question[] 转换为 EditorDoc,
 * 以便通过 structureToEditorDoc 回填到富文本编辑器。
 *
 * 与 editorDocToStructure 互为逆操作。
 */
export const examNodesToEditorDoc = (
  nodes: ExamNode[],
  questions: Question[],
  title: string
): EditorDoc => {
  const questionById = new Map<string, Question>()
  for (const q of questions) questionById.set(q.id, q)

  const editorQuestions: EditorQuestion[] = []
  const seenQuestionIds = new Set<string>()

  const buildQuestionFromNode = (node: ExamNode): EditorQuestion | null => {
    if (node.type !== "question" || !node.questionId) return null
    const q = questionById.get(node.questionId)
    if (!q) return null
    if (seenQuestionIds.has(q.id)) return null
    seenQuestionIds.add(q.id)

    const content = parseQuestionContent(q.content)
    return {
      id: q.id,
      type: toRichQuestionType(q.type, "single_choice"),
      score: node.score ?? 0,
      content,
    }
  }

  const convertNode = (node: ExamNode): EditorStructureNode | null => {
    if (node.type === "section") {
      const children: EditorStructureNode[] = []
      for (const child of node.children ?? []) {
        const converted = convertNode(child)
        if (converted) children.push(converted)
      }
      return {
        id: node.id || createId(),
        type: "section",
        title: node.title,
        level: node.level,
        children,
      }
    }
    if (node.type === "group") {
      const children: EditorStructureNode[] = []
      for (const child of node.children ?? []) {
        const converted = convertNode(child)
        if (converted) children.push(converted)
      }
      return {
        id: node.id || createId(),
        type: "group",
        title: node.title,
        instruction: node.instruction,
        children,
      }
    }
    if (node.type === "question") {
      const eq = buildQuestionFromNode(node)
      if (!eq) return null
      editorQuestions.push(eq)
      return {
        id: node.id || createId(),
        type: "question",
        questionId: eq.id,
        score: eq.score,
      }
    }
    return null
  }

  const structure: EditorStructureNode[] = []
  for (const node of nodes) {
    const converted = convertNode(node)
    if (converted) structure.push(converted)
  }

  return { title, questions: editorQuestions, structure }
}

/** 解析 Question.content(可能是 JSON 字符串或对象)为 RichQuestionContent */
const parseQuestionContent = (raw: unknown): EditorQuestion["content"] => {
  if (raw && typeof raw === "object") {
    return raw as EditorQuestion["content"]
  }
  if (typeof raw === "string") {
    try {
      const parsed: unknown = JSON.parse(raw)
      if (parsed && typeof parsed === "object") {
        return parsed as EditorQuestion["content"]
      }
      return { text: raw }
    } catch {
      return { text: raw }
    }
  }
  return { text: "" }
}
