/**
 * Mock 题库数据（content 域，P7 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 30 道题（5 类型 × 6 题，难度均匀分布 EASY/MEDIUM/HARD）
 * - 含 questionId/content/type/difficulty/textbookId/chapterId/kpId/score/answer/analysis
 * - 引用 textbooks.ts 中的前 5 本教材的章节与知识点
 */

import type {
  QuestionItem,
  QuestionType,
  QuestionDifficulty,
  QuestionsLibraryFilter,
  QuestionsLibraryPage,
  QuestionCreateInput,
  QuestionUpdateInput,
  QuestionBatchImportInput,
  QuestionBatchImportResult,
  QuestionBatchExportResult,
} from "@/lib/graphql-p7-exams";
import { MOCK_TEXTBOOK_DETAILS } from "./textbooks";

/** 题目类型枚举顺序 */
const QUESTION_TYPES: QuestionType[] = [
  "SINGLE_CHOICE",
  "MULTIPLE_CHOICE",
  "TRUE_FALSE",
  "FILL_BLANK",
  "SHORT_ANSWER",
];

/** 难度枚举 */
const DIFFICULTIES: QuestionDifficulty[] = ["EASY", "MEDIUM", "HARD"];

/** 中文类型标签（用于题目内容模板） */
const TYPE_LABEL: Record<QuestionType, string> = {
  SINGLE_CHOICE: "单项选择",
  MULTIPLE_CHOICE: "多项选择",
  TRUE_FALSE: "判断",
  FILL_BLANK: "填空",
  SHORT_ANSWER: "简答",
};

/** 题目内容模板 */
function questionContent(
  type: QuestionType,
  subject: string,
  kp: string,
  idx: number,
): string {
  const labels = TYPE_LABEL[type];
  if (type === "SINGLE_CHOICE" || type === "MULTIPLE_CHOICE") {
    return `【${labels}】${subject}·${kp}（题 ${idx}）：下列关于${kp}的描述，正确的是？\nA. 选项 A：基本概念表述\nB. 选项 B：进阶应用举例\nC. 选项 C：常见错误理解\nD. 选项 D：综合分析结论`;
  }
  if (type === "TRUE_FALSE") {
    return `【判断题】${subject}·${kp}（题 ${idx}）：${kp}的核心定义成立时，可以推出相关结论。（请判断对错）`;
  }
  if (type === "FILL_BLANK") {
    return `【填空题】${subject}·${kp}（题 ${idx}）：根据${kp}的基本原理，可得 ______，进而推出 ______。`;
  }
  return `【简答题】${subject}·${kp}（题 ${idx}）：请简述${kp}的定义、性质与典型应用场景。`;
}

/** 标准答案模板 */
function answerTemplate(type: QuestionType): string {
  switch (type) {
    case "SINGLE_CHOICE":
      return "B";
    case "MULTIPLE_CHOICE":
      return "A, C, D";
    case "TRUE_FALSE":
      return "正确";
    case "FILL_BLANK":
      return "对应公式结论；迁移应用结果";
    case "SHORT_ANSWER":
      return `${TYPE_LABEL[type]}标准答案：先阐述定义，再说明性质，最后给出两个典型应用示例。`;
  }
}

/** 解析模板 */
function analysisTemplate(type: QuestionType, kp: string): string {
  return `解析要点：本题考查${kp}。需先回顾基本定义，再结合选项/空缺判断正误；若涉及简答，应分层作答，做到逻辑清晰、有理有据。题型：${TYPE_LABEL[type]}。`;
}

/** 从前 5 本教材中收集可用 textbook/chapter/kp 三元组 */
interface TbkRef {
  textbookId: string;
  textbookName: string;
  chapterId: string;
  chapterName: string;
  kpId: string;
  kpName: string;
  subject: string;
}

function collectTextbookRefs(): TbkRef[] {
  const refs: TbkRef[] = [];
  const targetTextbooks = MOCK_TEXTBOOK_DETAILS.slice(0, 5);
  for (const tb of targetTextbooks) {
    for (const ch of tb.chapters) {
      for (const kp of ch.knowledgePoints) {
        refs.push({
          textbookId: tb.id,
          textbookName: tb.title,
          chapterId: ch.id,
          chapterName: ch.title,
          kpId: kp.id,
          kpName: kp.name,
          subject: tb.subject,
        });
      }
    }
  }
  return refs;
}

const TEXTBOOK_REFS = collectTextbookRefs();

/** 按 (类型索引 * 6 + 题内序号) 选取 textbook ref，保证 30 题覆盖前 5 本教材 */
function pickRef(typeIdx: number, qIdx: number): TbkRef {
  const seed = (typeIdx * 6 + qIdx) % TEXTBOOK_REFS.length;
  // 题目均匀分布在所有可用 ref 上
  const ref = TEXTBOOK_REFS[seed];
  if (!ref) {
    // 兜底（理论上不会进入，因为 TEXTBOOK_REFS 至少有数十条）
    const fallback = TEXTBOOK_REFS[0];
    if (!fallback) {
      throw new Error("textbook refs empty");
    }
    return fallback;
  }
  return ref;
}

/** 生成 30 道题 */
function generateQuestions(): QuestionItem[] {
  const now = Date.now();
  const items: QuestionItem[] = [];
  // 5 类型 × 6 题 = 30
  QUESTION_TYPES.forEach((type, typeIdx) => {
    for (let q = 0; q < 6; q++) {
      const ref = pickRef(typeIdx, q);
      const difficulty = DIFFICULTIES[q % DIFFICULTIES.length] ?? "MEDIUM";
      const idx = typeIdx * 6 + q + 1;
      const questionId = `q-${String(idx).padStart(3, "0")}`;
      items.push({
        questionId,
        content: questionContent(type, ref.subject, ref.kpName, idx),
        type,
        difficulty,
        textbookId: ref.textbookId,
        textbookName: ref.textbookName,
        chapterId: ref.chapterId,
        chapterName: ref.chapterName,
        kpId: ref.kpId,
        kpName: ref.kpName,
        score: type === "SHORT_ANSWER" ? 10 : type === "FILL_BLANK" ? 5 : 4,
        answer: answerTemplate(type),
        analysis: analysisTemplate(type, ref.kpName),
        createdAt: new Date(now - idx * 60_000).toISOString(),
        updatedAt: new Date(now - idx * 30_000).toISOString(),
      });
    }
  });
  return items;
}

/** 内存中题库（支持运行时插入/更新/删除），导出供 exam-analytics 等模块消费初始快照 */
export let MOCK_QUESTIONS: QuestionItem[] = generateQuestions();

/** 计数器（用于新建题目 ID） */
let questionCounter = MOCK_QUESTIONS.length;

/** 按筛选条件过滤题库（分页） */
export function filterQuestions(
  filter: QuestionsLibraryFilter,
): QuestionsLibraryPage {
  const q = (filter.q ?? "").trim().toLowerCase();
  const type = filter.type ?? null;
  const difficulty = filter.difficulty ?? null;
  const kp = filter.kp ?? null;
  const textbook = filter.textbook ?? null;
  const chapter = filter.chapter ?? null;
  const page = Math.max(1, filter.page ?? 1);
  const pageSize = Math.max(1, filter.pageSize ?? 20);

  let items = MOCK_QUESTIONS;
  if (q) {
    items = items.filter(
      (it) =>
        it.content.toLowerCase().includes(q) ||
        it.kpName?.toLowerCase().includes(q),
    );
  }
  if (type) {
    items = items.filter((it) => it.type === type);
  }
  if (difficulty) {
    items = items.filter((it) => it.difficulty === difficulty);
  }
  if (kp && kp !== "all") {
    items = items.filter((it) => it.kpId === kp);
  }
  if (textbook && textbook !== "all") {
    items = items.filter((it) => it.textbookId === textbook);
  }
  if (chapter && chapter !== "all") {
    items = items.filter((it) => it.chapterId === chapter);
  }

  // 按 createdAt 倒序
  const sorted = [...items].sort((a, b) =>
    b.createdAt.localeCompare(a.createdAt),
  );
  const total = sorted.length;
  const start = (page - 1) * pageSize;
  const paged = sorted.slice(start, start + pageSize);
  return { items: paged, total, page, pageSize };
}

/** 按 ID 查找题目 */
export function findQuestion(questionId: string): QuestionItem | null {
  return MOCK_QUESTIONS.find((q) => q.questionId === questionId) ?? null;
}

/** 创建题目（持久化到内存） */
export function createMockQuestion(
  input: QuestionCreateInput,
): QuestionItem {
  questionCounter += 1;
  const now = new Date().toISOString();
  const questionId = `q-${String(questionCounter).padStart(3, "0")}`;
  // 查找教材/章节/知识点名称（如引用存在）
  let textbookName: string | null = null;
  let chapterName: string | null = null;
  let kpName: string | null = null;
  if (input.textbookId) {
    const tb = MOCK_TEXTBOOK_DETAILS.find((t) => t.id === input.textbookId);
    textbookName = tb?.title ?? null;
    if (tb && input.chapterId) {
      const ch = tb.chapters.find((c) => c.id === input.chapterId);
      chapterName = ch?.title ?? null;
      if (ch && input.kpId) {
        const kp = ch.knowledgePoints.find((k) => k.id === input.kpId);
        kpName = kp?.name ?? null;
      }
    }
  }
  const item: QuestionItem = {
    questionId,
    content: input.content,
    type: input.type,
    difficulty: input.difficulty,
    textbookId: input.textbookId ?? null,
    textbookName,
    chapterId: input.chapterId ?? null,
    chapterName,
    kpId: input.kpId ?? null,
    kpName,
    score: input.score,
    answer: input.answer,
    analysis: input.analysis ?? "",
    createdAt: now,
    updatedAt: now,
  };
  MOCK_QUESTIONS = [item, ...MOCK_QUESTIONS];
  return item;
}

/** 更新题目 */
export function updateMockQuestion(
  input: QuestionUpdateInput,
): QuestionItem | null {
  const idx = MOCK_QUESTIONS.findIndex((q) => q.questionId === input.questionId);
  if (idx === -1) return null;
  const existing = MOCK_QUESTIONS[idx];
  if (!existing) return null;
  // 解析新的 textbook/chapter/kp 名称
  let textbookName = existing.textbookName;
  let chapterName = existing.chapterName;
  let kpName = existing.kpName;
  if (input.textbookId !== undefined) {
    const tb = MOCK_TEXTBOOK_DETAILS.find((t) => t.id === input.textbookId);
    textbookName = tb?.title ?? null;
  }
  if (input.chapterId !== undefined) {
    const tb = MOCK_TEXTBOOK_DETAILS.find(
      (t) => t.id === (input.textbookId ?? existing.textbookId),
    );
    const ch = tb?.chapters.find((c) => c.id === input.chapterId);
    chapterName = ch?.title ?? null;
  }
  if (input.kpId !== undefined) {
    const tb = MOCK_TEXTBOOK_DETAILS.find(
      (t) => t.id === (input.textbookId ?? existing.textbookId),
    );
    const ch = tb?.chapters.find(
      (c) => c.id === (input.chapterId ?? existing.chapterId),
    );
    const kp = ch?.knowledgePoints.find((k) => k.id === input.kpId);
    kpName = kp?.name ?? null;
  }
  const updated: QuestionItem = {
    ...existing,
    content: input.content ?? existing.content,
    type: input.type ?? existing.type,
    difficulty: input.difficulty ?? existing.difficulty,
    textbookId: input.textbookId !== undefined ? input.textbookId : existing.textbookId,
    textbookName,
    chapterId: input.chapterId !== undefined ? input.chapterId : existing.chapterId,
    chapterName,
    kpId: input.kpId !== undefined ? input.kpId : existing.kpId,
    kpName,
    score: input.score ?? existing.score,
    answer: input.answer ?? existing.answer,
    analysis: input.analysis ?? existing.analysis,
    updatedAt: new Date().toISOString(),
  };
  // 替换 store 中的元素
  const next = [...MOCK_QUESTIONS];
  next[idx] = updated;
  MOCK_QUESTIONS = next;
  return updated;
}

/** 删除题目 */
export function deleteMockQuestion(questionId: string): boolean {
  const idx = MOCK_QUESTIONS.findIndex((q) => q.questionId === questionId);
  if (idx === -1) return false;
  MOCK_QUESTIONS = MOCK_QUESTIONS.filter((q) => q.questionId !== questionId);
  return true;
}

/** 批量导入 */
export function batchImportQuestions(
  input: QuestionBatchImportInput,
): QuestionBatchImportResult {
  let importedCount = 0;
  let failedCount = 0;
  const errors: string[] = [];
  input.items.forEach((item, i) => {
    if (!item.content || !item.type || !item.difficulty) {
      failedCount += 1;
      errors.push(`第 ${i + 1} 题缺少必填字段（content/type/difficulty）`);
      return;
    }
    createMockQuestion(item);
    importedCount += 1;
  });
  return { importedCount, failedCount, errors };
}

/** 批量导出 */
export function batchExportQuestions(
  filter: QuestionsLibraryFilter,
): QuestionBatchExportResult {
  const page = filterQuestions({ ...filter, page: 1, pageSize: 10_000 });
  return {
    items: page.items,
    exportedAt: new Date().toISOString(),
  };
}

/** 题目类型选项（用于筛选/创建下拉） */
export const QUESTION_TYPE_OPTIONS: ReadonlyArray<{
  value: QuestionType;
  label: string;
}> = QUESTION_TYPES.map((t) => ({ value: t, label: TYPE_LABEL[t] }));

/** 难度选项 */
export const QUESTION_DIFFICULTY_OPTIONS: ReadonlyArray<{
  value: QuestionDifficulty;
  label: string;
}> = [
  { value: "EASY", label: "简单" },
  { value: "MEDIUM", label: "中等" },
  { value: "HARD", label: "困难" },
];

/** 题目类型中文映射（外部消费） */
export const QUESTION_TYPE_LABEL: Record<QuestionType, string> = TYPE_LABEL;

/** 难度中文映射 */
export const QUESTION_DIFFICULTY_LABEL: Record<QuestionDifficulty, string> = {
  EASY: "简单",
  MEDIUM: "中等",
  HARD: "困难",
};
