// 课案状态
// M3 审核工作流：扩展为 draft → submitted → approved → published → rejected → archived
// - draft: 草稿（教师可编辑）
// - submitted: 已提交审核（教师不可编辑，等待审核）
// - approved: 审核通过（教师可发布）
// - published: 已发布（学生/家长可查看）
// - rejected: 审核驳回（教师可编辑后重新提交）
// - archived: 已归档
export type LessonPlanStatus =
  | "draft"
  | "submitted"
  | "approved"
  | "published"
  | "rejected"
  | "archived";

// M3 审核工作流：状态机迁移规则
export const LESSON_PLAN_STATUS_TRANSITIONS: Record<LessonPlanStatus, LessonPlanStatus[]> = {
  draft: ["submitted", "archived"],
  submitted: ["approved", "rejected"],
  approved: ["published", "draft"],
  published: ["draft"],
  rejected: ["draft", "archived"],
  archived: ["draft"],
};

// M3 审核工作流：判断是否可编辑（教师视角）
export function isEditableStatus(status: LessonPlanStatus): boolean {
  return status === "draft" || status === "rejected";
}

// M3 审核工作流：判断是否可提交审核
export function isSubmittableStatus(status: LessonPlanStatus): boolean {
  return status === "draft" || status === "rejected";
}

// M3 审核工作流：判断是否可审核（教研组长视角）
export function isReviewableStatus(status: LessonPlanStatus): boolean {
  return status === "submitted";
}

// M3 审核工作流：判断是否可发布
export function isPublishableStatus(status: LessonPlanStatus): boolean {
  return status === "approved";
}

// Block 类型枚举（教学节点）
export type BlockType =
  | "objective"
  | "key_point"
  | "import"
  | "new_teaching"
  | "consolidation"
  | "summary"
  | "homework"
  | "blackboard"
  | "text_study"
  | "exercise"
  | "rich_text"
  | "reflection";

// 正文节点类型（特殊：不可拖动，画布中央）
export type TextbookContentNodeType = "textbook_content";

// 节点类型联合（用于 React Flow 注册）
export type LessonNodeType = BlockType | TextbookContentNodeType;

// ---- 各 Block 数据接口 ----

// 富文本类
export interface RichTextBlockData {
  html: string;
  knowledgePointIds: string[];
  /**
   * V5-5：节点内嵌入的多媒体附件引用。
   * 字段 attachmentId 关联 lessonPlanAttachments 表；url 为渲染用相对/绝对地址；
   * kind 决定 UI 渲染（image/audio/video/file）。
   * 旧数据无此字段时按空数组处理（document-migration 兼容）。
   */
  attachments?: RichTextAttachment[];
}

/** V5-5：富文本节点内的附件引用 */
export interface RichTextAttachment {
  attachmentId: string;
  fileId: string;
  displayName: string;
  /** MIME 大类，决定 UI 渲染方式 */
  kind: "image" | "audio" | "video" | "file";
  /** 渲染用 URL（由 /api/upload 返回的 url） */
  url: string;
  /** MIME 类型（如 image/png），用于 <source> 标签 */
  mimeType?: string;
}

// 文本研习
export interface TextStudyAnnotation {
  id: string;
  anchor: { start: number; end: number };
  nodeType: string;
  title: string;
  note: string;
  color: "yellow" | "green";
}

export interface TextStudyBlockData {
  sourceText: string;
  annotations: TextStudyAnnotation[];
  knowledgePointIds: string[];
}

// 练习
export type ExercisePurpose = "class_practice" | "after_class_homework";

export interface InlineQuestionContent {
  content: unknown;
  type: string;
  difficulty: number;
  knowledgePointIds: string[];
}

export interface ExerciseItem {
  questionId: string;
  source: "bank" | "inline";
  score: number;
  order: number;
  inlineContent?: InlineQuestionContent;
}

export interface ExerciseBlockData {
  items: ExerciseItem[];
  purpose: ExercisePurpose;
  knowledgePointIds: string[];
  publishedAssignmentId?: string;
  publishedExamId?: string;
  publishedAt?: string;
}

// 教学目标（三维目标）
export interface ObjectiveItem {
  dimension: "knowledge" | "process" | "emotion";
  text: string;
}

export interface ObjectiveBlockData {
  objectives: ObjectiveItem[];
}

// 重难点
export interface KeyPointItem {
  type: "key" | "difficult";
  text: string;
}

export interface KeyPointBlockData {
  keyPoints: KeyPointItem[];
}

// 导入
export interface ImportBlockData {
  method: "question" | "situation" | "review" | "other";
  prompt: string;
  durationMin: number;
}

// 新授
export interface NewTeachingPoint {
  knowledgePointIds: string[];
  outline: string;
  boardNotes: string;
}

export interface NewTeachingBlockData {
  teachingPoints: NewTeachingPoint[];
}

// 小结
export interface SummaryBlockData {
  summaryPoints: string[];
  homeworkPreview: string;
}

// 作业
export interface HomeworkAssignment {
  type: "exercise" | "reading" | "writing";
  refId?: string;
  description: string;
}

export interface HomeworkBlockData {
  assignments: HomeworkAssignment[];
}

// 板书设计
export interface BlackboardBlockData {
  layout: "structure" | "mindmap" | "text";
  content: string;
  knowledgePointIds: string[];
}

// 教学反思
export interface ReflectionItem {
  aspect: "effectiveness" | "problems" | "improvements";
  text: string;
}

export interface ReflectionBlockData {
  reflection: ReflectionItem[];
}

// 正文节点数据
export interface TextbookContentNodeData {
  chapterId: string;
  content: string;       // Markdown 正文（缓存）
  zoom: number;          // 缩放比例 0.5-2.0
}

// Block 数据联合类型
export type BlockData =
  | RichTextBlockData
  | TextStudyBlockData
  | ExerciseBlockData
  | ObjectiveBlockData
  | KeyPointBlockData
  | ImportBlockData
  | NewTeachingBlockData
  | SummaryBlockData
  | HomeworkBlockData
  | BlackboardBlockData
  | ReflectionBlockData;

// V5-15 T1：教学阶段（用于画布节点分组与可视化排序）
// - import: 导入环节
// - new_teaching: 新授环节
// - consolidation: 巩固练习
// - summary: 总结提升
// 未设置（undefined）表示教师未显式归类
export type TeachingStage = "import" | "new_teaching" | "consolidation" | "summary";

// V5-15 i18n 键后缀（与 TeachingStage 一一对应）
export const TEACHING_STAGE_KEYS = ["import", "new_teaching", "consolidation", "summary"] as const;

// V5-18 W6：差异化教学标记（按学生水平分组）
// - basic: 基础（全员必做）
// - intermediate: 提高（多数学生）
// - advanced: 拓展（学有余力）
export type DifferentiationLevel = "basic" | "intermediate" | "advanced";

// V5-18 i18n 键后缀
export const DIFFERENTIATION_LEVEL_KEYS = ["basic", "intermediate", "advanced"] as const;

// Block 联合
export interface Block {
  id: string;
  type: BlockType;
  title: string;
  data: BlockData;
  order: number;
  /** V5-15 T1：教学阶段分组（可选，教师可显式归类节点）*/
  stage?: TeachingStage;
  /** V5-18 W6：差异化教学标记（可选，标注此节点的目标学生水平）*/
  differentiation?: DifferentiationLevel;
}

// 教学节点（Block + 画布坐标）
export interface LessonPlanNode extends Block {
  position: { x: number; y: number };
}

// 正文节点（不可拖动）
export interface TextbookContentNode {
  id: string;
  type: TextbookContentNodeType;
  title: string;
  data: TextbookContentNodeData;
  order: number;
  position: { x: number; y: number };
  draggable: false;
}

// 节点联合
export type AnyLessonPlanNode = LessonPlanNode | TextbookContentNode;

// ---- 锚点 ----
export type AnchorType = "range" | "point";

export interface NodeAnchor {
  id: string;
  nodeId: string;          // 关联的教学节点 ID
  type: AnchorType;
  start: number;           // 正文纯文本偏移量
  end?: number;            // range 锚定的结束偏移
  textPreview?: string;    // range 锚定的文字预览（用于失效重定位）
  invalid?: boolean;       // 正文变更后无法重定位时标记为失效
}

// ---- 边 ----
export type LessonEdgeType = "anchor" | "flow";

// 基础边
export interface LessonPlanEdge {
  id: string;
  source: string;
  target: string;
  sourceHandle?: string | null;
  targetHandle?: string | null;
}

// 锚点连线（教学节点 → 正文节点）
export interface AnchorEdge extends LessonPlanEdge {
  type: "anchor";
  anchorId: string;
}

// 流程连线（教学节点 → 教学节点）
export interface FlowEdge extends LessonPlanEdge {
  type: "flow";
}

export type AnyLessonPlanEdge = AnchorEdge | FlowEdge;

// ---- 文档版本 ----

// v1（旧格式，向后兼容读取）
export interface LessonPlanDocumentV1 {
  version: 1;
  blocks: Block[];
}

// v2（节点图格式）
export interface LessonPlanDocumentV2 {
  version: 2;
  nodes: LessonPlanNode[];
  edges: LessonPlanEdge[];
}

// v3（课文锚点画布格式）
export interface LessonPlanDocument {
  version: 3;
  textbookContentNodeId: string;
  nodes: AnyLessonPlanNode[];
  edges: AnyLessonPlanEdge[];
  anchors: NodeAnchor[];
}

// 课案
export interface LessonPlan {
  id: string;
  title: string;
  textbookId: string | null;
  chapterId: string | null;
  coursePlanItemId: string | null;
  subjectId: string | null;
  gradeId: string | null;
  templateId: string | null;
  templateName: string | null;
  content: LessonPlanDocument;
  status: LessonPlanStatus;
  creatorId: string;
  lastSavedAt: string | null;
  createdAt: string;
  updatedAt: string;
}

// 版本
export interface LessonPlanVersion {
  id: string;
  planId: string;
  versionNo: number;
  label: string | null;
  content: LessonPlanDocument;
  isAuto: boolean;
  creatorId: string;
  createdAt: string;
}

// 模板
export type TemplateType = "system" | "personal";
export type TemplateScope =
  | "regular"
  | "review"
  | "experiment"
  | "inquiry"
  | "blank"
  | "custom";

export interface TemplateBlockSkeleton {
  type: BlockType;
  title: string;
  hint?: string;
}

export interface LessonPlanTemplate {
  id: string;
  name: string;
  type: TemplateType;
  scope: TemplateScope;
  blocks: TemplateBlockSkeleton[];
  creatorId: string | null;
  createdAt: string;
  updatedAt: string;
}

// 版本摘要（用于卡片上的版本选择器）
export interface LessonPlanVersionSummary {
  id: string;
  title: string;
  status: LessonPlanStatus;
  updatedAt: string;
  lastSavedAt: string | null;
}

// 列表项（带教材/章节名）
export interface LessonPlanListItem extends LessonPlan {
  textbookTitle: string | null;
  chapterTitle: string | null;
  subjectName: string | null;
  gradeName: string | null;
  creatorName: string | null;
  /** 同一备课的版本数（≥1，=1 表示无多版本）*/
  versionCount: number;
  /** 同一备课的所有版本摘要（按 updatedAt 降序）*/
  versions: LessonPlanVersionSummary[];
}

// ActionState（与项目现有约定一致）
export type ActionState<T = unknown> = {
  success: boolean;
  message?: string;
  errors?: Record<string, string[]>;
  data?: T;
};
