/**
 * Mock 错题本数据（error-book 域，P7-insights 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 班级 × 6 学科 错题统计
 * - 章节薄弱度（5 学科 × 10 章节）
 * - 知识点薄弱度（5 学科 × 20 知识点）
 * - Top10 高频错题
 * - 学生错题分组（前 5 学生）
 */

import type {
  ErrorBook,
  ErrorBookSummary,
  ErrorBookClassComparison,
  ErrorBookChapterWeakness,
  ErrorBookKpWeakness,
  ErrorBookStudentGroup,
  ErrorBookTopQuestion,
} from "@/lib/graphql-p7-insights";

/** 5 个班级 */
const CLASSES = [
  { id: "550e8400-e29b-41d4-a716-446655440010", name: "高三(1)班", base: 120 },
  { id: "550e8400-e29b-41d4-a716-446655440011", name: "高三(2)班", base: 110 },
  { id: "550e8400-e29b-41d4-a716-446655440012", name: "高三(3)班", base: 135 },
  { id: "550e8400-e29b-41d4-a716-446655440013", name: "高三(4)班", base: 105 },
  { id: "550e8400-e29b-41d4-a716-446655440014", name: "高三(5)班", base: 95 },
] as const;

/** 6 学科（错题本用） */
export const ERROR_BOOK_SUBJECTS = [
  "语文",
  "数学",
  "英语",
  "物理",
  "化学",
  "生物",
] as const;

/** 章节模板（每学科 10 章节） */
const CHAPTER_TEMPLATES: Record<string, string[]> = {
  语文: ["现代文阅读", "古诗词鉴赏", "文言文阅读", "成语运用", "病句辨析", "论述类文本", "实用类文本", "语言运用", "议论文写作", "记叙文写作"],
  数学: ["集合与逻辑", "函数与导数", "三角函数", "数列", "立体几何", "解析几何", "概率统计", "不等式", "复数", "向量"],
  英语: ["听力", "阅读理解", "完形填空", "语法填空", "短文改错", "书面表达", "七选五", "词汇运用", "句型转换", "翻译"],
  物理: ["力学", "运动学", "动力学", "能量守恒", "动量", "电学", "磁学", "光学", "热学", "近代物理"],
  化学: ["化学键", "化学反应", "化学平衡", "电离", "水解", "氧化还原", "元素周期", "有机化学", "实验化学", "计算化学"],
  生物: ["细胞", "遗传", "变异", "进化", "生态", "植物激素", "人体生理", "免疫", "微生物", "生物技术"],
};

/** 知识点薄弱度模板（每学科 10 知识点，雷达图用） */
const KP_TEMPLATES: Record<string, string[]> = {
  语文: ["主旨概括", "细节理解", "推理判断", "词义猜测", "论证分析", "情感把握", "手法鉴赏", "结构梳理", "语言品味", "文化常识"],
  数学: ["函数定义域", "单调性", "奇偶性", "导数运算", "极值最值", "数列求和", "向量运算", "概率计算", "几何证明", "参数方程"],
  英语: ["主旨题", "细节题", "推理题", "词义题", "作者态度", "完形填空", "语法结构", "词汇辨析", "句型转换", "书面表达"],
  物理: ["受力分析", "运动方程", "能量守恒", "动量守恒", "电场", "磁场", "电磁感应", "光学成像", "热学定律", "原子结构"],
  化学: ["化学键类型", "反应速率", "化学平衡", "电离平衡", "水解平衡", "氧化剂", "还原剂", "元素周期", "官能团", "实验操作"],
  生物: ["细胞结构", "光合作用", "细胞呼吸", "有丝分裂", "减数分裂", "遗传规律", "基因突变", "生态系统", "激素调节", "免疫机制"],
};

/** 班级对比 */
export function getClassErrorComparison(
  subject: string,
): ErrorBookClassComparison[] {
  return CLASSES.map((c) => {
    // 学科偏移：理科偏多错题
    const subjOffset = subject === "数学" || subject === "物理" ? 20 : 0;
    const subjOffset2 = subject === "语文" || subject === "英语" ? -10 : 0;
    return {
      classId: c.id,
      className: c.name,
      errorCount: c.base + subjOffset + subjOffset2,
    };
  });
}

/** 章节薄弱度（10 章节） */
export function getChapterWeakness(
  subject: string,
): ErrorBookChapterWeakness[] {
  const chapters = CHAPTER_TEMPLATES[subject] ?? CHAPTER_TEMPLATES["数学"]!;
  return chapters.map((ch, i) => ({
    chapter: ch,
    errorCount: 20 + i * 5 + ((subject.length + i) % 7) * 3,
  }));
}

/** 知识点薄弱度（10 知识点，雷达图用） */
export function getKpWeakness(subject: string): ErrorBookKpWeakness[] {
  const kps = KP_TEMPLATES[subject] ?? KP_TEMPLATES["数学"]!;
  return kps.map((kp, i) => ({
    knowledgePoint: kp,
    errorRate: Math.max(20, Math.min(85, 30 + i * 4 + ((subject.length + i) % 5) * 3)),
  }));
}

/** 学生错题分组（前 5 学生） */
export function getStudentGroups(
  subject: string,
): ErrorBookStudentGroup[] {
  const students = [
    { id: "stu-001", name: "学生01", base: 28 },
    { id: "stu-002", name: "学生02", base: 25 },
    { id: "stu-003", name: "学生03", base: 22 },
    { id: "stu-004", name: "学生04", base: 18 },
    { id: "stu-005", name: "学生05", base: 15 },
  ];
  return students.map((s) => {
    const subjOffset = subject === "数学" ? 5 : 0;
    return {
      studentId: s.id,
      studentName: s.name,
      errorCount: s.base + subjOffset,
      topErrors: [
        {
          questionId: `q-${s.id}-1`,
          content: `${subject}高频错题示例：${subject}基础知识应用题（题干较长时显示前 100 字）`,
          errorRate: 0.75,
        },
        {
          questionId: `q-${s.id}-2`,
          content: `${subject}中档题：${subject}综合题分析题（含图形或长文本描述）`,
          errorRate: 0.62,
        },
        {
          questionId: `q-${s.id}-3`,
          content: `${subject}概念辨析题：${subject}易错概念对比题`,
          errorRate: 0.55,
        },
      ],
    };
  });
}

/** Top10 高频错题 */
export function getTopQuestions(subject: string): ErrorBookTopQuestion[] {
  const items: ErrorBookTopQuestion[] = [];
  for (let i = 1; i <= 10; i++) {
    items.push({
      questionId: `q-top-${subject}-${i}`,
      content: `【${subject}·高频】第 ${i} 题：${subject}综合应用题示例（题干内容较长，此处显示前 100 字以便预览，完整题干在详情页展示）`,
      errorRate: 0.85 - i * 0.05,
      subject,
    });
  }
  return items;
}

/** 完整错题本（聚合查询） */
export function getErrorBook(
  subject: string,
  classId?: string | null,
): ErrorBook {
  const classComparison = getClassErrorComparison(subject);
  const targetClass = classId
    ? classComparison.find((c) => c.classId === classId)
    : null;
  const totalErrors = targetClass
    ? targetClass.errorCount
    : classComparison.reduce((acc, c) => acc + c.errorCount, 0);

  const summary: ErrorBookSummary = {
    totalErrors,
    highFreqErrors: Math.floor(totalErrors * 0.15),
    weakKpCount: 6,
    avgErrorRate: 0.42,
    trendUp: subject === "数学" || subject === "物理",
  };

  return {
    subject,
    classId: classId ?? "",
    summary,
    classComparison,
    chapterWeakness: getChapterWeakness(subject),
    kpWeakness: getKpWeakness(subject),
    studentGroups: getStudentGroups(subject),
    topQuestions: getTopQuestions(subject),
  };
}
