/**
 * Mock 扫描批改数据（P7-advanced：扫描批改模块）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 个提交的扫描图片 URL（placeholder）
 * - 已识别作答 + AI 评分建议
 * - 按 submissionId 查询扫描批改视图 + 保存批改
 */

import type {
  SubmissionScanGrading,
  ScanImage,
  ScanGradingItem,
  SaveScanGradingInput,
  SaveScanGradingResult,
} from "@/lib/graphql-p7-advanced";

/** 5 个提交定义 */
const SUBMISSION_DEFS: Array<{
  submissionId: string;
  homeworkTitle: string;
  studentName: string;
  studentNo: string;
}> = [
  {
    submissionId: "scan-sub-001",
    homeworkTitle: "函数练习题",
    studentName: "张明",
    studentNo: "20260001",
  },
  {
    submissionId: "scan-sub-002",
    homeworkTitle: "导数应用题",
    studentName: "李华",
    studentNo: "20260002",
  },
  {
    submissionId: "scan-sub-003",
    homeworkTitle: "数列综合练习",
    studentName: "王芳",
    studentNo: "20260003",
  },
  {
    submissionId: "scan-sub-004",
    homeworkTitle: "立体几何作业",
    studentName: "刘洋",
    studentNo: "20260004",
  },
  {
    submissionId: "scan-sub-005",
    homeworkTitle: "解析几何专题",
    studentName: "陈静",
    studentNo: "20260005",
  },
];

/** 生成扫描图片列表（每份提交 2-3 页，用 placeholder） */
function generateScanImages(submissionId: string): ScanImage[] {
  const pageCount = 2 + (submissionId.charCodeAt(submissionId.length - 1) % 2);
  const images: ScanImage[] = [];
  for (let i = 1; i <= pageCount; i++) {
    images.push({
      imageId: `img-${submissionId}-${i}`,
      // placeholder 图片：用 picsum 占位（项目规则不禁止 URL）
      url: `https://picsum.photos/seed/${submissionId}-${i}/800/1100`,
      page: i,
    });
  }
  return images;
}

/** 题目模板（4 题） */
const QUESTION_TEMPLATES: Array<{
  title: string;
  maxScore: number;
  recognizedAnswer: string;
  aiSuggestedScore: number;
  aiSuggestion: string;
}> = [
  {
    title: "求函数 f(x) = x² - 2x + 1 在 [0, 2] 上的极值",
    maxScore: 25,
    recognizedAnswer: "f(1) = 0 为极小值",
    aiSuggestedScore: 22,
    aiSuggestion: "答案正确，步骤基本完整。建议补充极值点二阶导数验证。",
  },
  {
    title: "选择题：函数 y = ln(x) 的导数是",
    maxScore: 20,
    recognizedAnswer: "B. y = 1/x",
    aiSuggestedScore: 20,
    aiSuggestion: "选择题答案正确。",
  },
  {
    title: "计算定积分 ∫₀¹ (2x + 1) dx",
    maxScore: 25,
    recognizedAnswer: "积分结果为 2",
    aiSuggestedScore: 18,
    aiSuggestion: "结果正确，但缺少积分上下限代入的中间步骤。",
  },
  {
    title: "论述：导数在实际问题中的应用",
    maxScore: 30,
    recognizedAnswer: "导数可应用于最优化问题、物理学中的瞬时速度等",
    aiSuggestedScore: 24,
    aiSuggestion: "论述方向正确，但较为简略。建议补充至少一个具体实例。",
  },
];

/** 按 submissionId 查询扫描批改视图 */
export function findScanGrading(
  submissionId: string,
): SubmissionScanGrading | null {
  const def = SUBMISSION_DEFS.find((s) => s.submissionId === submissionId);
  if (!def) return null;

  // 确定 prev/next 导航链
  const idx = SUBMISSION_DEFS.findIndex((s) => s.submissionId === submissionId);
  const prevSubmissionId = idx > 0 ? (SUBMISSION_DEFS[idx - 1]?.submissionId ?? null) : null;
  const nextSubmissionId =
    idx >= 0 && idx < SUBMISSION_DEFS.length - 1
      ? (SUBMISSION_DEFS[idx + 1]?.submissionId ?? null)
      : null;

  const items: ScanGradingItem[] = QUESTION_TEMPLATES.map((q, i) => ({
    questionId: `${submissionId}-q-${String(i + 1).padStart(3, "0")}`,
    questionTitle: q.title,
    questionOrder: i + 1,
    maxScore: q.maxScore,
    recognizedAnswer: q.recognizedAnswer,
    aiSuggestedScore: q.aiSuggestedScore,
    aiSuggestion: q.aiSuggestion,
    score: null,
    feedback: null,
  }));

  const now = Date.now();
  return {
    submissionId: def.submissionId,
    homeworkTitle: def.homeworkTitle,
    studentName: def.studentName,
    studentNo: def.studentNo,
    submittedAt: new Date(now - 2 * 60 * 60 * 1000).toISOString(),
    images: generateScanImages(def.submissionId),
    items,
    prevSubmissionId,
    nextSubmissionId,
  };
}

/** 保存扫描批改（mock：返回 totalScore + 时间戳） */
export function saveScanGrading(
  input: SaveScanGradingInput,
): SaveScanGradingResult {
  const totalScore = input.items.reduce((acc, item) => acc + (item.score || 0), 0);
  return {
    submissionId: input.submissionId,
    totalScore,
    savedAt: new Date().toISOString(),
  };
}
