/**
 * Mock 自适应练习数据（practice 域，P7-insights 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 班级练习统计（含 5 指标）
 * - 类型分布（5 类型：单选/多选/判断/填空/简答）
 * - 知识点薄弱度（10 知识点）
 * - 学生排名（20 学生）
 * - 未参与提醒（最近 7 天未练习）
 */

import type {
  PracticeAnalytics,
  PracticeSummary,
  PracticeClassComparison,
  PracticeTypeBreakdown,
  PracticeKpWeakness,
  PracticeStudentRank,
  PracticeInactiveStudent,
} from "@/lib/graphql-p7-insights";

/** 5 个班级 */
const CLASSES = [
  { id: "550e8400-e29b-41d4-a716-446655440010", name: "高三(1)班", sessions: 240, accuracy: 0.78, completion: 0.85, participation: 0.92 },
  { id: "550e8400-e29b-41d4-a716-446655440011", name: "高三(2)班", sessions: 220, accuracy: 0.82, completion: 0.88, participation: 0.94 },
  { id: "550e8400-e29b-41d4-a716-446655440012", name: "高三(3)班", sessions: 260, accuracy: 0.75, completion: 0.82, participation: 0.89 },
  { id: "550e8400-e29b-41d4-a716-446655440013", name: "高三(4)班", sessions: 200, accuracy: 0.80, completion: 0.86, participation: 0.91 },
  { id: "550e8400-e29b-41d4-a716-446655440014", name: "高三(5)班", sessions: 280, accuracy: 0.85, completion: 0.90, participation: 0.95 },
] as const;

/** 5 类型分布 */
const TYPE_DEFS = [
  { type: "单选题", count: 380, ratio: 0.42 },
  { type: "多选题", count: 180, ratio: 0.20 },
  { type: "判断题", count: 120, ratio: 0.13 },
  { type: "填空题", count: 140, ratio: 0.16 },
  { type: "简答题", count: 80, ratio: 0.09 },
] as const;

/** 10 知识点（薄弱度） */
const KP_DEFS = [
  { knowledgePoint: "函数与导数", accuracy: 0.62 },
  { knowledgePoint: "数列", accuracy: 0.68 },
  { knowledgePoint: "立体几何", accuracy: 0.72 },
  { knowledgePoint: "解析几何", accuracy: 0.58 },
  { knowledgePoint: "概率统计", accuracy: 0.75 },
  { knowledgePoint: "实数运算", accuracy: 0.85 },
  { knowledgePoint: "三角函数", accuracy: 0.70 },
  { knowledgePoint: "不等式", accuracy: 0.66 },
  { knowledgePoint: "复数", accuracy: 0.80 },
  { knowledgePoint: "向量", accuracy: 0.74 },
] as const;

/** 生成学生排名（20 学生） */
function generateRankings(classId: string): PracticeStudentRank[] {
  const cls = CLASSES.find((c) => c.id === classId) ?? CLASSES[0]!;
  const baseAccuracy = cls.accuracy;
  const ranks: PracticeStudentRank[] = [];
  for (let i = 1; i <= 20; i++) {
    const delta = ((i - 10) * 0.02);
    const accuracy = Math.max(0.4, Math.min(0.98, baseAccuracy - delta));
    ranks.push({
      rank: i,
      studentId: `stu-${classId.slice(-4)}-${String(i).padStart(3, "0")}`,
      studentName: `学生${String(i).padStart(2, "0")}`,
      studentNo: `2026${String(i).padStart(3, "0")}`,
      totalSessions: Math.round(cls.sessions / 20) + (i % 3),
      accuracy: Math.round(accuracy * 100) / 100,
      weakKp: i % 3 === 0 ? "函数与导数" : i % 3 === 1 ? "解析几何" : "概率统计",
    });
  }
  ranks.sort((a, b) => b.accuracy - a.accuracy);
  return ranks.map((r, i) => ({ ...r, rank: i + 1 }));
}

/** 生成未参与学生（5 名） */
function generateInactiveStudents(classId: string): PracticeInactiveStudent[] {
  return [
    { studentId: `stu-${classId.slice(-4)}-007`, studentName: "学生07", lastActiveDays: 7 },
    { studentId: `stu-${classId.slice(-4)}-011`, studentName: "学生11", lastActiveDays: 8 },
    { studentId: `stu-${classId.slice(-4)}-014`, studentName: "学生14", lastActiveDays: 10 },
    { studentId: `stu-${classId.slice(-4)}-018`, studentName: "学生18", lastActiveDays: 9 },
    { studentId: `stu-${classId.slice(-4)}-020`, studentName: "学生20", lastActiveDays: 12 },
  ];
}

/** 班级对比表 */
export function getClassComparison(): PracticeClassComparison[] {
  return CLASSES.map((c) => ({
    classId: c.id,
    className: c.name,
    totalSessions: c.sessions,
    completionRate: c.completion,
    avgAccuracy: c.accuracy,
    participationRate: c.participation,
    weakKpCount: Math.floor((1 - c.accuracy) * 20),
  }));
}

/** 类型分布 */
export function getTypeBreakdown(): PracticeTypeBreakdown[] {
  return TYPE_DEFS.map((t) => ({ ...t }));
}

/** 知识点薄弱度 */
export function getKpWeakness(): PracticeKpWeakness[] {
  return KP_DEFS.map((k) => ({ ...k }));
}

/** 聚合查询 */
export function getPracticeAnalytics(
  classId?: string | null,
): PracticeAnalytics {
  const allClasses = getClassComparison();
  const targetClass = classId
    ? allClasses.find((c) => c.classId === classId)
    : null;

  // 单班级视图 vs 全部视图
  const targetSessions = targetClass ? targetClass.totalSessions : allClasses.reduce((acc, c) => acc + c.totalSessions, 0);
  const targetAccuracy = targetClass
    ? targetClass.avgAccuracy
    : allClasses.reduce((acc, c) => acc + c.avgAccuracy, 0) / allClasses.length;
  const targetCompletion = targetClass
    ? targetClass.completionRate
    : allClasses.reduce((acc, c) => acc + c.completionRate, 0) / allClasses.length;
  const targetParticipation = targetClass
    ? targetClass.participationRate
    : allClasses.reduce((acc, c) => acc + c.participationRate, 0) / allClasses.length;

  const summary: PracticeSummary = {
    totalSessions: targetSessions,
    completionRate: Math.round(targetCompletion * 100) / 100,
    avgAccuracy: Math.round(targetAccuracy * 100) / 100,
    weakKpCount: 6,
    participationRate: Math.round(targetParticipation * 100) / 100,
  };

  const targetClassId = classId ?? CLASSES[0]!.id;

  return {
    classId: classId ?? "",
    summary,
    classComparison: allClasses,
    typeBreakdown: getTypeBreakdown(),
    kpWeakness: getKpWeakness(),
    rankings: generateRankings(targetClassId),
    inactiveStudents: generateInactiveStudents(targetClassId),
  };
}
