import type { JSONContent } from "@tiptap/react"

export type RichQuestionType =
  | "single_choice"
  | "multiple_choice"
  | "judgment"
  | "text"
  | "composite"

/**
 * 可直接持久化为独立 question 的题型（不含 composite）。
 * composite 必须通过 subQuestions 拆分创建，无法直接落库为单条 question 记录。
 */
export type StandaloneQuestionType = Exclude<RichQuestionType, "composite">

const RICH_QUESTION_TYPE_SET: ReadonlySet<string> = new Set<string>([
  "single_choice",
  "multiple_choice",
  "judgment",
  "text",
  "composite",
])

const STANDALONE_QUESTION_TYPE_SET: ReadonlySet<string> = new Set<string>([
  "single_choice",
  "multiple_choice",
  "judgment",
  "text",
])

/**
 * 运行时类型守卫：验证 unknown 值是否为合法的 RichQuestionType。
 * 用于消除 Tiptap attrs / AI 返回值 / DB 字段等边界处的 `as RichQuestionType` 断言。
 */
export function isRichQuestionType(v: unknown): v is RichQuestionType {
  return typeof v === "string" && RICH_QUESTION_TYPE_SET.has(v)
}

/**
 * 运行时类型守卫：验证 unknown 值是否为可直接持久化的题型（不含 composite）。
 * 用于 actions/data-access 在写入 questions 表前收窄类型。
 */
export function isStandaloneQuestionType(v: unknown): v is StandaloneQuestionType {
  return typeof v === "string" && STANDALONE_QUESTION_TYPE_SET.has(v)
}

/**
 * 安全转换：将 unknown 收窄为 RichQuestionType，非法值回退到 fallback（默认 "single_choice"）。
 */
export function toRichQuestionType(v: unknown, fallback: RichQuestionType = "single_choice"): RichQuestionType {
  return isRichQuestionType(v) ? v : fallback
}

/**
 * 安全转换：将 RichQuestionType 收窄为 StandaloneQuestionType。
 * composite 会回退到 fallback（默认 "text"），调用方应优先过滤 composite。
 */
export function toStandaloneQuestionType(
  v: RichQuestionType,
  fallback: StandaloneQuestionType = "text"
): StandaloneQuestionType {
  return v === "composite" ? fallback : v
}

export interface RichQuestionContent {
  text: string
  options?: Array<{ id: string; text: string; isCorrect?: boolean }>
  blanks?: Array<{ id: string; answer?: string; score?: number }>
  images?: Array<{ fileId: string; url: string; alt?: string }>
  subQuestions?: Array<{ id: string; text: string; answer?: string; score?: number }>
  correctAnswer?: unknown
}

export interface EditorQuestion {
  id: string
  type: RichQuestionType
  score: number
  content: RichQuestionContent
}

/** 结构节点类型:section=分卷, group=大题, question=题目 */
export type EditorStructureNodeType = "section" | "group" | "question"

export interface EditorStructureNode {
  id: string
  type: EditorStructureNodeType
  title?: string
  /** 大题说明(如"每小题3分") */
  instruction?: string
  /** 分卷层级(1=卷, 2=部分) */
  level?: number
  questionId?: string
  score?: number
  /** 自动统计:题目数(不含结构节点) */
  questionCount?: number
  /** 自动统计:总分(子题累加) */
  totalScore?: number
  children?: EditorStructureNode[]
}

export interface EditorDoc {
  title: string
  questions: EditorQuestion[]
  structure: EditorStructureNode[]
}

/** 用于编辑器与试卷结构互转的 JSONContent 别名 */
export type EditorJSONContent = JSONContent
