/**
 * Mock 监考数据（P7-advanced：监考模块）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 场考试 × 30 学生监考状态
 * - 监考事件流（20 个事件）
 * - 按 examId 查询监考状态 + 提交事件
 */

import type {
  ProctoringStatus,
  ProctoringSummary,
  ProctoringStudent,
  ProctoringEvent,
  ProctoringStudentStatus,
  ProctoringEventInput,
} from "@/lib/graphql-p7-advanced";

/** 5 场考试定义 */
const EXAM_DEFS: Array<{
  examId: string;
  title: string;
  expectedCount: number;
  isProctoring: boolean;
}> = [
  { examId: "proctor-exam-001", title: "2026 春季期中考试", expectedCount: 30, isProctoring: true },
  { examId: "proctor-exam-002", title: "单元测试 - 函数与导数", expectedCount: 28, isProctoring: true },
  { examId: "proctor-exam-003", title: "月考 - 数学综合", expectedCount: 32, isProctoring: false },
  { examId: "proctor-exam-004", title: "期末模拟考", expectedCount: 30, isProctoring: true },
  { examId: "proctor-exam-005", title: "随堂测验 - 解析几何", expectedCount: 25, isProctoring: false },
];

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

/** 学生姓名池（30 个） */
const STUDENT_NAMES = [
  "张明", "李华", "王芳", "刘洋", "陈静", "杨帆", "赵磊", "孙丽", "周强", "吴敏",
  "郑浩", "钱莹", "冯涛", "陈雪", "褚伟", "卫国", "蒋雯", "沈鹏", "韩雪", "杨光",
  "朱琳", "秦宇", "尤佳", "许诺", "何欢", "吕娜", "施磊", "张超", "孔慧", "曹阳",
];

/** 生成单场考试的学生监考状态列表 */
function generateProctoringStudents(examId: string, count: number): ProctoringStudent[] {
  const list: ProctoringStudent[] = [];
  const now = Date.now();
  for (let i = 0; i < count; i++) {
    const seed = strToSeed(`${examId}-stu-${i}`);
    const r = seededRandom(seed);
    let status: ProctoringStudentStatus;
    if (r > 0.85) status = "flagged";
    else if (r > 0.7) status = "submitted";
    else if (r > 0.1) status = "online";
    else status = "offline";

    list.push({
      studentId: `stu-${examId}-${String(i + 1).padStart(3, "0")}`,
      studentName: STUDENT_NAMES[i] ?? `学生${i + 1}`,
      studentNo: `2026${String(i + 1).padStart(4, "0")}`,
      status,
      lastEventAt: status === "offline" ? null : new Date(now - i * 60 * 1000).toISOString(),
      ipAddress: status === "offline" ? null : `192.168.1.${100 + i}`,
    });
  }
  return list;
}

/** 生成监考事件流（按时间倒序） */
function generateProctoringEvents(examId: string): ProctoringEvent[] {
  const EVENT_TYPES: Array<{ type: ProctoringEvent["eventType"]; note: string }> = [
    { type: "WARNING", note: "切屏到其他应用" },
    { type: "FLAG", note: "多次切屏，疑似作弊" },
    { type: "NOTE", note: "教师手动备注：已提醒" },
    { type: "WARNING", note: "浏览器失去焦点" },
    { type: "FLAG", note: "检测到复制粘贴行为" },
    { type: "NOTE", note: "学生请求上厕所" },
    { type: "WARNING", note: "网络连接不稳定" },
    { type: "FLAG", note: "全屏模式退出" },
    { type: "NOTE", note: "已重新连接监考" },
    { type: "WARNING", note: "麦克风静音" },
  ];
  const now = Date.now();
  const events: ProctoringEvent[] = [];
  for (let i = 0; i < 20; i++) {
    const seed = strToSeed(`${examId}-evt-${i}`);
    const def = EVENT_TYPES[i % EVENT_TYPES.length] ?? EVENT_TYPES[0]!;
    const studentIdx = Math.floor(seededRandom(seed + 1) * 30);
    events.push({
      eventId: `evt-${examId}-${String(i + 1).padStart(3, "0")}`,
      examId,
      studentId: `stu-${examId}-${String(studentIdx + 1).padStart(3, "0")}`,
      studentName: STUDENT_NAMES[studentIdx] ?? `学生${studentIdx + 1}`,
      studentNo: `2026${String(studentIdx + 1).padStart(4, "0")}`,
      eventType: def.type,
      note: def.note,
      createdAt: new Date(now - i * 3 * 60 * 1000).toISOString(),
    });
  }
  return events;
}

/** 生成监考摘要 */
function generateSummary(examId: string): ProctoringSummary {
  const def = EXAM_DEFS.find((e) => e.examId === examId) ?? EXAM_DEFS[0]!;
  const students = generateProctoringStudents(examId, def.expectedCount);
  const onlineCount = students.filter((s) => s.status === "online").length;
  const submittedCount = students.filter((s) => s.status === "submitted").length;
  const flaggedCount = students.filter((s) => s.status === "flagged").length;
  const now = Date.now();
  return {
    examId,
    expectedCount: def.expectedCount,
    onlineCount,
    submittedCount,
    flaggedCount,
    isProctoring: def.isProctoring,
    startedAt: def.isProctoring ? new Date(now - 30 * 60 * 1000).toISOString() : null,
  };
}

/** 按考试 ID 查询监考状态（摘要 + 学生列表 + 近期事件） */
export function findProctoringStatus(examId: string): ProctoringStatus {
  const summary = generateSummary(examId);
  const students = generateProctoringStudents(examId, summary.expectedCount);
  const recentEvents = generateProctoringEvents(examId);
  return {
    summary,
    students,
    recentEvents,
  };
}

/** 提交监考事件（mock：返回事件 ID + 创建时间） */
export function createProctoringEvent(
  input: ProctoringEventInput,
): { eventId: string; createdAt: string } {
  return {
    eventId: `evt-${input.examId}-${Math.random().toString(36).slice(2, 8)}`,
    createdAt: new Date().toISOString(),
  };
}
