/**
 * Mock 考试分析数据（core-edu 域，P7 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 场考试 × 30 学生 × 20 题
 * - 分数分布、及格率、每题正确率、知识点掌握度、班级对比、历次趋势、学生排名
 */

import type {
  ExamAnalytics,
  ExamAnalyticsSummary,
  ExamScoreBand,
  ExamQuestionAccuracy,
  ExamKpMastery,
  ExamClassComparison,
  ExamHistoryTrend,
  ExamStudentRank,
  ExamBuildStructure,
  ExamBuildNode,
} from "@/lib/graphql-p7-exams";
import type { QuestionItem } from "@/lib/graphql-p7-exams";
import type { ExamDetail } from "@/lib/graphql";
import { MOCK_QUESTIONS } from "./questions";
import { EXTENDED_CLASSES } from "./grades-extended";

/** 5 场考试定义 */
interface ExamDef {
  examId: string;
  title: string;
  classId: string;
  className: string;
  examDate: string;
  totalScore: number;
}

const NOW = Date.now();
const DAY = 24 * 60 * 60 * 1000;

const EXAM_DEFS: ExamDef[] = [
  {
    examId: "exam-ana-001",
    title: "2026 春季期中考试",
    classId: EXTENDED_CLASSES[0]?.id ?? "c-001",
    className: EXTENDED_CLASSES[0]?.name ?? "高三(1)班",
    examDate: new Date(NOW - 7 * DAY).toISOString(),
    totalScore: 150,
  },
  {
    examId: "exam-ana-002",
    title: "单元测试 - 函数与导数",
    classId: EXTENDED_CLASSES[0]?.id ?? "c-001",
    className: EXTENDED_CLASSES[0]?.name ?? "高三(1)班",
    examDate: new Date(NOW - 14 * DAY).toISOString(),
    totalScore: 100,
  },
  {
    examId: "exam-ana-003",
    title: "月考 - 数学综合",
    classId: EXTENDED_CLASSES[1]?.id ?? "c-002",
    className: EXTENDED_CLASSES[1]?.name ?? "高三(2)班",
    examDate: new Date(NOW - 21 * DAY).toISOString(),
    totalScore: 120,
  },
  {
    examId: "exam-ana-004",
    title: "周测 - 解析几何",
    classId: EXTENDED_CLASSES[2]?.id ?? "c-003",
    className: EXTENDED_CLASSES[2]?.name ?? "高三(3)班",
    examDate: new Date(NOW - 3 * DAY).toISOString(),
    totalScore: 80,
  },
  {
    examId: "exam-ana-005",
    title: "阶段测验 - 概率统计",
    classId: EXTENDED_CLASSES[3]?.id ?? "c-004",
    className: EXTENDED_CLASSES[3]?.name ?? "高三(4)班",
    examDate: new Date(NOW - 1 * DAY).toISOString(),
    totalScore: 100,
  },
];

/** 确定性伪随机（与 grades-extended 一致） */
function seededRandom(seed: number): number {
  const x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
}

function strToSeed(s: string): number {
  let h = 0;
  for (let i = 0; i < s.length; i++) {
    h = (h * 31 + s.charCodeAt(i)) | 0;
  }
  return Math.abs(h) + 1;
}

/** 计算等级 */
function scoreToLevel(score: number, total: number): ExamStudentRank["level"] {
  const ratio = total > 0 ? score / total : 0;
  if (ratio >= 0.9) return "A";
  if (ratio >= 0.8) return "B";
  if (ratio >= 0.7) return "C";
  if (ratio >= 0.6) return "D";
  return "E";
}

/** 生成 30 个学生成绩（按考试 ID 稳定） */
function generateStudentScores(
  examId: string,
  totalScore: number,
): Array<{
  studentId: string;
  studentName: string;
  studentNo: string;
  totalScore: number;
}> {
  const base = totalScore * 0.7; // 均分约 70%
  const result: Array<{
    studentId: string;
    studentName: string;
    studentNo: string;
    totalScore: number;
  }> = [];
  for (let i = 1; i <= 30; i++) {
    const seed = strToSeed(`${examId}-stu-${i}`);
    const delta = Math.round((seededRandom(seed) - 0.4) * totalScore * 0.4);
    const score = Math.max(
      0,
      Math.min(totalScore, Math.round(base + delta)),
    );
    result.push({
      studentId: `stu-${examId.slice(-3)}-${String(i).padStart(3, "0")}`,
      studentName: `学生${String(i).padStart(2, "0")}`,
      studentNo: `2026${String(i).padStart(3, "0")}`,
      totalScore: score,
    });
  }
  result.sort((a, b) => b.totalScore - a.totalScore);
  return result;
}

/** 生成 5 段分数分布 */
function generateDistribution(
  scores: number[],
  total: number,
): ExamScoreBand[] {
  const bands: ExamScoreBand[] = [
    { label: "0-59", min: 0, max: 59, count: 0 },
    { label: "60-69", min: 60, max: 69, count: 0 },
    { label: "70-79", min: 70, max: 79, count: 0 },
    { label: "80-89", min: 80, max: 89, count: 0 },
    { label: "90-100", min: 90, max: 100, count: 0 },
  ];
  // 按 0-100 百分比归一化（total != 100 时换算）
  scores.forEach((s) => {
    const pct = total > 0 ? (s / total) * 100 : 0;
    if (pct < 60) bands[0]!.count += 1;
    else if (pct < 70) bands[1]!.count += 1;
    else if (pct < 80) bands[2]!.count += 1;
    else if (pct < 90) bands[3]!.count += 1;
    else bands[4]!.count += 1;
  });
  return bands;
}

/** 选取前 20 题（不足 20 则循环补齐） */
function pick20Questions(): QuestionItem[] {
  const items: QuestionItem[] = [];
  for (let i = 0; i < 20; i++) {
    const q = MOCK_QUESTIONS[i % MOCK_QUESTIONS.length];
    if (q) items.push(q);
  }
  return items;
}

const EXAM_QUESTIONS = pick20Questions();

/** 生成每题正确率 */
function generateQuestionAccuracy(
  examId: string,
): ExamQuestionAccuracy[] {
  return EXAM_QUESTIONS.map((q, i) => {
    const seed = strToSeed(`${examId}-qa-${i}`);
    const correctRate = Math.round(40 + seededRandom(seed) * 55); // 40-95
    const avgScore = Math.round((q.score * correctRate) / 100);
    return {
      questionId: q.questionId,
      questionTitle: q.content.slice(0, 40),
      order: i + 1,
      correctRate,
      avgScore,
      maxScore: q.score,
    };
  });
}

/** 5 个知识点（用于雷达图） */
const KP_NAMES = [
  "函数与导数",
  "数列",
  "立体几何",
  "解析几何",
  "概率统计",
];

/** 生成知识点掌握度 */
function generateKpMastery(examId: string): ExamKpMastery[] {
  return KP_NAMES.map((name, i) => {
    const seed = strToSeed(`${examId}-kp-${i}`);
    const mastery = Math.round(50 + seededRandom(seed) * 45); // 50-95
    return { knowledgePoint: name, mastery };
  });
}

/** 生成班级对比 */
function generateClassComparison(
  targetClassId: string,
  avg: number,
): ExamClassComparison[] {
  return EXTENDED_CLASSES.map((c) => {
    const seed = strToSeed(`cc-${c.id}`);
    const delta = Math.round((seededRandom(seed) - 0.5) * 16);
    const classAvg = Math.max(0, Math.round(avg + delta));
    return {
      classId: c.id,
      className: c.name,
      avg: classAvg,
      significant: c.id === targetClassId ? false : Math.abs(delta) >= 7,
    };
  });
}

/** 生成历次考试趋势 */
function generateHistoryTrend(): ExamHistoryTrend[] {
  return EXAM_DEFS.map((e) => {
    const seed = strToSeed(`ht-${e.examId}`);
    const avg = Math.round(60 + seededRandom(seed) * 25); // 60-85
    return {
      examTitle: e.title,
      examDate: e.examDate,
      avg,
    };
  });
}

/** 生成考试分析完整数据 */
export function generateExamAnalytics(examId: string): ExamAnalytics | null {
  const def = EXAM_DEFS.find((e) => e.examId === examId);
  if (!def) return null;
  const studentScores = generateStudentScores(examId, def.totalScore);
  const scores = studentScores.map((s) => s.totalScore);
  const sum = scores.reduce((acc, s) => acc + s, 0);
  const avg = Math.round((sum / scores.length) * 10) / 10;
  const max = Math.max(...scores);
  const min = Math.min(...scores);
  const passCount = scores.filter(
    (s) => s / def.totalScore >= 0.6,
  ).length;
  const passRate = Math.round((passCount / scores.length) * 1000) / 10;

  const summary: ExamAnalyticsSummary = {
    expectedCount: 30,
    attendedCount: 30,
    avgScore: avg,
    maxScore: max,
    minScore: min,
    passRate,
  };

  const distribution = generateDistribution(scores, def.totalScore);
  const questionAccuracy = generateQuestionAccuracy(examId);
  const knowledgeMastery = generateKpMastery(examId);
  const classComparison = generateClassComparison(def.classId, avg);
  const historyTrend = generateHistoryTrend();

  const rankings: ExamStudentRank[] = studentScores.map((s, i) => ({
    rank: i + 1,
    studentId: s.studentId,
    studentName: s.studentName,
    studentNo: s.studentNo,
    totalScore: s.totalScore,
    level: scoreToLevel(s.totalScore, def.totalScore),
  }));

  return {
    examId,
    examTitle: def.title,
    summary,
    distribution,
    questionAccuracy,
    knowledgeMastery,
    classComparison,
    historyTrend,
    rankings,
  };
}

/**
 * 生成试卷结构（组卷页用）
 *
 * - 从题库取前 20 题作为候选分页
 * - 已选题目：前 4 题（默认排序）
 */
export function generateExamBuildStructure(
  examId: string,
  examDetail: ExamDetail | null,
  candidatePage: number,
  candidatePageSize: number,
): ExamBuildStructure | null {
  // 默认 4 题已选，分数按 examDetail.totalScore 平均分摊
  const selectedCount = 4;
  const totalScore = examDetail?.totalScore ?? 100;
  const passScore = Math.round(totalScore * 0.6);
  const duration = examDetail?.duration ?? 120;
  const title = examDetail?.title ?? "未命名考试";

  // 取前 4 道题作为已选
  const picked = EXAM_QUESTIONS.slice(0, selectedCount);
  const perScore = Math.floor(totalScore / selectedCount);
  const remainder = totalScore - perScore * selectedCount;
  const selected: ExamBuildNode[] = picked.map((q, i) => ({
    questionId: q.questionId,
    score: perScore + (i === 0 ? remainder : 0),
    sortOrder: i + 1,
    content: q.content,
    type: q.type,
    difficulty: q.difficulty,
  }));

  // 题库候选分页（前 20 题）
  const start = (candidatePage - 1) * candidatePageSize;
  const candidatesItems = EXAM_QUESTIONS.slice(start, start + candidatePageSize);
  const candidates = {
    items: candidatesItems,
    total: EXAM_QUESTIONS.length,
    page: candidatePage,
    pageSize: candidatePageSize,
  };

  return {
    examId,
    title,
    totalScore,
    passScore,
    duration,
    selected,
    candidates,
  };
}

/** 所有 mock 考试定义（外部可消费） */
export const MOCK_EXAM_ANALYTICS_DEFS = EXAM_DEFS;
