/**
 * Mock 作业提交数据（P7：作业批改链路）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 10 个作业 × 30 学生提交记录（统计维度）
 * - 单份提交含题目作答 + AI 评分建议
 * - 按 submissionId 查找详情（含上一份/下一份导航）
 */

import type {
  HomeworkSubmissionStat,
  HomeworkSubmissionDetail,
  SubmissionAnswer,
  GradeSubmissionInput,
  GradeSubmissionResult,
} from "@/lib/graphql-p7-grades";
import { EXTENDED_CLASSES } from "./grades-extended";

/** 10 个作业定义（跨 5 个班级） */
const HOMEWORK_DEFS: Array<{
  homeworkId: string;
  title: string;
  classId: string;
  className: string;
  status: HomeworkSubmissionStat["status"];
  totalCount: number;
  submittedCount: number;
  gradedCount: number;
  avgScore: number | null;
}> = [
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440010-hw-001",
    title: "函数练习题",
    classId: EXTENDED_CLASSES[0]?.id ?? "",
    className: EXTENDED_CLASSES[0]?.name ?? "",
    status: "published",
    totalCount: 32,
    submittedCount: 28,
    gradedCount: 20,
    avgScore: 82,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440010-hw-002",
    title: "导数应用题",
    classId: EXTENDED_CLASSES[0]?.id ?? "",
    className: EXTENDED_CLASSES[0]?.name ?? "",
    status: "graded",
    totalCount: 32,
    submittedCount: 30,
    gradedCount: 30,
    avgScore: 78,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440011-hw-001",
    title: "数列综合练习",
    classId: EXTENDED_CLASSES[1]?.id ?? "",
    className: EXTENDED_CLASSES[1]?.name ?? "",
    status: "published",
    totalCount: 30,
    submittedCount: 25,
    gradedCount: 10,
    avgScore: 85,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440011-hw-002",
    title: "立体几何作业",
    classId: EXTENDED_CLASSES[1]?.id ?? "",
    className: EXTENDED_CLASSES[1]?.name ?? "",
    status: "published",
    totalCount: 30,
    submittedCount: 22,
    gradedCount: 5,
    avgScore: null,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440012-hw-001",
    title: "解析几何专题",
    classId: EXTENDED_CLASSES[2]?.id ?? "",
    className: EXTENDED_CLASSES[2]?.name ?? "",
    status: "draft",
    totalCount: 28,
    submittedCount: 0,
    gradedCount: 0,
    avgScore: null,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440012-hw-002",
    title: "概率统计练习",
    classId: EXTENDED_CLASSES[2]?.id ?? "",
    className: EXTENDED_CLASSES[2]?.name ?? "",
    status: "published",
    totalCount: 28,
    submittedCount: 26,
    gradedCount: 26,
    avgScore: 80,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440013-hw-001",
    title: "三角函数复习",
    classId: EXTENDED_CLASSES[3]?.id ?? "",
    className: EXTENDED_CLASSES[3]?.name ?? "",
    status: "graded",
    totalCount: 30,
    submittedCount: 30,
    gradedCount: 30,
    avgScore: 88,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440013-hw-002",
    title: "向量与复数",
    classId: EXTENDED_CLASSES[3]?.id ?? "",
    className: EXTENDED_CLASSES[3]?.name ?? "",
    status: "published",
    totalCount: 30,
    submittedCount: 18,
    gradedCount: 8,
    avgScore: 75,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440014-hw-001",
    title: "不等式练习",
    classId: EXTENDED_CLASSES[4]?.id ?? "",
    className: EXTENDED_CLASSES[4]?.name ?? "",
    status: "published",
    totalCount: 32,
    submittedCount: 30,
    gradedCount: 12,
    avgScore: 90,
  },
  {
    homeworkId: "550e8400-e29b-41d4-a716-446655440014-hw-002",
    title: "圆锥曲线综合",
    classId: EXTENDED_CLASSES[4]?.id ?? "",
    className: EXTENDED_CLASSES[4]?.name ?? "",
    status: "published",
    totalCount: 32,
    submittedCount: 27,
    gradedCount: 3,
    avgScore: null,
  },
];

/** 按作业维度统计提交（可按 classId / status 过滤） */
export function generateHomeworkSubmissionStats(
  classId?: string,
  status?: string,
): HomeworkSubmissionStat[] {
  const now = Date.now();
  return HOMEWORK_DEFS.filter((h) => {
    if (classId && h.classId !== classId) return false;
    if (status && h.status !== status) return false;
    return true;
  }).map((h) => ({
    homeworkId: h.homeworkId,
    title: h.title,
    classId: h.classId,
    className: h.className,
    status: h.status,
    dueDate: new Date(now + 3 * 24 * 60 * 60 * 1000).toISOString(),
    totalCount: h.totalCount,
    submittedCount: h.submittedCount,
    gradedCount: h.gradedCount,
    avgScore: h.avgScore,
  }));
}

/** 4 道题目模板（用于生成作答详情） */
const QUESTION_DEFS: Array<{
  title: string;
  type: SubmissionAnswer["questionType"];
  maxScore: number;
  correctAnswer: string;
}> = [
  {
    title: "求函数 f(x) = x² - 2x + 1 在 [0, 2] 上的极值",
    type: "SHORT_ANSWER",
    maxScore: 25,
    correctAnswer: "极小值 f(1) = 0，极大值 f(0) = f(2) = 1",
  },
  {
    title: "选择题：函数 y = ln(x) 的导数是",
    type: "SINGLE_CHOICE",
    maxScore: 20,
    correctAnswer: "B. y = 1/x",
  },
  {
    title: "计算定积分 ∫₀¹ (2x + 1) dx",
    type: "SHORT_ANSWER",
    maxScore: 25,
    correctAnswer: "∫₀¹ (2x + 1) dx = [x² + x]₀¹ = 1 + 1 = 2",
  },
  {
    title: "论述：导数在实际问题中的应用",
    type: "ESSAY",
    maxScore: 30,
    correctAnswer: "（参考答案）导数可用于求极值、最值、变化率分析等……",
  },
];

const STUDENT_ANSWERS = [
  "f(1) = 0 为极小值",
  "B",
  "积分结果为 2",
  "导数可应用于最优化问题、物理学中的瞬时速度等",
];

const AI_SUGGESTIONS = [
  "答案正确，步骤清晰。建议补充极值点验证过程。",
  "选择题正确。",
  "计算正确，但缺少积分上下限代入步骤。",
  "论述较为简略，建议补充具体实例说明。",
];

/** 确定性伪随机 */
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;
}

/**
 * 按作业 ID 生成所有提交详情列表
 *
 * 每份提交包含 4 道题作答 + AI 评分建议。
 * 同一作业下的提交列表共享 prevSubmissionId / nextSubmissionId 链。
 */
export function generateAssignmentSubmissions(
  homeworkId: string,
): HomeworkSubmissionDetail[] {
  const def = HOMEWORK_DEFS.find((h) => h.homeworkId === homeworkId);
  const totalCount = def?.submittedCount ?? 5;
  const now = Date.now();
  const list: HomeworkSubmissionDetail[] = [];

  for (let i = 1; i <= totalCount; i++) {
    const studentId = `stu-${homeworkId.slice(-4)}-${String(i).padStart(3, "0")}`;
    const submissionId = `${homeworkId}-sub-${String(i).padStart(3, "0")}`;
    const isGraded = def ? i <= def.gradedCount : false;

    const answers: SubmissionAnswer[] = QUESTION_DEFS.map((q, qi) => {
      const seed = strToSeed(`${submissionId}-${qi}`);
      const isCorrect = seededRandom(seed) > 0.3;
      const score = isCorrect ? q.maxScore : Math.floor(q.maxScore * 0.5);
      return {
        questionId: `${submissionId}-q-${String(qi + 1).padStart(3, "0")}`,
        questionTitle: q.title,
        questionType: q.type,
        maxScore: q.maxScore,
        studentAnswer: STUDENT_ANSWERS[qi] ?? "（未作答）",
        correctAnswer: q.correctAnswer,
        score: isGraded ? score : null,
        feedback: isGraded ? AI_SUGGESTIONS[qi] ?? null : null,
        aiSuggestion: AI_SUGGESTIONS[qi] ?? null,
      };
    });

    const totalScore = isGraded
      ? answers.reduce((acc, a) => acc + (a.score ?? 0), 0)
      : null;

    list.push({
      submissionId,
      homeworkId,
      homeworkTitle: def?.title ?? "作业详情",
      classId: def?.classId ?? "",
      className: def?.className ?? "",
      studentId,
      studentName: `学生${String(i).padStart(2, "0")}`,
      studentNo: `2026${String(i).padStart(3, "0")}`,
      status: isGraded ? "GRADED" : "SUBMITTED",
      submittedAt: new Date(now - i * 60 * 60 * 1000).toISOString(),
      totalScore,
      answers,
      prevSubmissionId: null,
      nextSubmissionId: null,
    });
  }

  // 建立 prev / next 链
  list.forEach((item, idx) => {
    item.prevSubmissionId = idx > 0 ? (list[idx - 1]?.submissionId ?? null) : null;
    item.nextSubmissionId =
      idx < list.length - 1 ? (list[idx + 1]?.submissionId ?? null) : null;
  });

  return list;
}

/** 按 submissionId 查找单份提交详情 */
export function findSubmissionDetail(
  submissionId: string,
): HomeworkSubmissionDetail | null {
  // submissionId 规约：${homeworkId}-sub-XXX
  const match = submissionId.match(/^(.+)-sub-\d+$/);
  if (!match) return null;
  const homeworkId = match[1] ?? "";
  const list = generateAssignmentSubmissions(homeworkId);
  return list.find((s) => s.submissionId === submissionId) ?? null;
}

/** 批改单份提交（mock：返回 GRADED 状态 + totalScore） */
export function gradeSubmission(
  input: GradeSubmissionInput,
): GradeSubmissionResult {
  // 若提供 questionScores，汇总；否则用 input.score
  const totalScore = input.questionScores
    ? input.questionScores.reduce((acc, q) => acc + q.score, 0)
    : input.score;
  return {
    submissionId: input.submissionId,
    status: "GRADED",
    totalScore,
    feedback: input.feedback ?? null,
  };
}

/** AI 批量评分建议（mock：对每份提交返回 AI 建议分数） */
export function generateAiBatchGrading(
  homeworkId: string,
): Array<{ submissionId: string; suggestedScore: number; suggestion: string }> {
  const list = generateAssignmentSubmissions(homeworkId);
  return list
    .filter((s) => s.status === "SUBMITTED")
    .map((s) => {
      const suggestedScore = s.answers.reduce(
        (acc, a) => acc + Math.floor(a.maxScore * 0.8),
        0,
      );
      return {
        submissionId: s.submissionId,
        suggestedScore,
        suggestion: "AI 建议分数基于作答完整度评估，请教师复核。",
      };
    });
}
