/**
 * Mock 诊断数据（diagnostic 域，P7-insights 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 个班级诊断（每班 10 知识点掌握度 + 学生排名）
 * - 5 个学生诊断（雷达图 + 班级对比 + 报告列表）
 * - 诊断报告列表（按 type + status 筛选）
 */

import type {
  DiagnosticReportItem,
  DiagnosticReportType,
  DiagnosticReportStatus,
  ClassDiagnostic,
  StudentDiagnostic,
  DiagnosticKpMastery,
  DiagnosticStudentRank,
  DiagnosticRadarPoint,
} from "@/lib/graphql-p7-insights";

/** 5 个班级（复用 grades-extended 的 class id 保持一致） */
export const DIAGNOSTIC_CLASSES = [
  { id: "550e8400-e29b-41d4-a716-446655440010", name: "高三(1)班" },
  { id: "550e8400-e29b-41d4-a716-446655440011", name: "高三(2)班" },
  { id: "550e8400-e29b-41d4-a716-446655440012", name: "高三(3)班" },
  { id: "550e8400-e29b-41d4-a716-446655440013", name: "高三(4)班" },
  { id: "550e8400-e29b-41d4-a716-446655440014", name: "高三(5)班" },
] as const;

/** 10 个知识点（数学/语文混合） */
const KNOWLEDGE_POINTS = [
  "函数与导数",
  "数列",
  "立体几何",
  "解析几何",
  "概率统计",
  "实数运算",
  "文言文基础",
  "现代文阅读",
  "古诗词鉴赏",
  "议论文写作",
] as const;

/** 班级平均基准（用于确定性 mock） */
const CLASS_BASE: Record<string, number> = {
  "550e8400-e29b-41d4-a716-446655440010": 78,
  "550e8400-e29b-41d4-a716-446655440011": 82,
  "550e8400-e29b-41d4-a716-446655440012": 75,
  "550e8400-e29b-41d4-a716-446655440013": 80,
  "550e8400-e29b-41d4-a716-446655440014": 85,
};

/** 确定性伪随机 */
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 median(values: number[]): number {
  if (values.length === 0) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 !== 0
    ? (sorted[mid] ?? 0)
    : ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2;
}

/** 诊断报告列表 mock（12 条） */
const REPORT_DEFS: Array<{
  id: string;
  title: string;
  type: DiagnosticReportType;
  targetType: string;
  status: DiagnosticReportStatus;
  createdAt: string;
}> = [
  { id: "dr-001", title: "高三(1)班 期中诊断报告", type: "CLASS", targetType: "高三(1)班", status: "PUBLISHED", createdAt: "2026-07-01T09:00:00Z" },
  { id: "dr-002", title: "学生01 个人诊断报告", type: "INDIVIDUAL", targetType: "学生01", status: "PUBLISHED", createdAt: "2026-07-02T10:30:00Z" },
  { id: "dr-003", title: "高三年级 期中诊断", type: "GRADE", targetType: "高三年级", status: "PUBLISHED", createdAt: "2026-07-03T14:15:00Z" },
  { id: "dr-004", title: "高三(2)班 月考诊断", type: "CLASS", targetType: "高三(2)班", status: "DRAFT", createdAt: "2026-07-04T11:00:00Z" },
  { id: "dr-005", title: "学生02 个人诊断", type: "INDIVIDUAL", targetType: "学生02", status: "DRAFT", createdAt: "2026-07-05T08:45:00Z" },
  { id: "dr-006", title: "高三(3)班 单元诊断", type: "CLASS", targetType: "高三(3)班", status: "ARCHIVED", createdAt: "2026-06-28T16:20:00Z" },
  { id: "dr-007", title: "学生03 个人诊断", type: "INDIVIDUAL", targetType: "学生03", status: "PUBLISHED", createdAt: "2026-07-06T09:00:00Z" },
  { id: "dr-008", title: "高三年级 期末诊断", type: "GRADE", targetType: "高三年级", status: "DRAFT", createdAt: "2026-07-07T13:30:00Z" },
  { id: "dr-009", title: "高三(4)班 月考诊断", type: "CLASS", targetType: "高三(4)班", status: "PUBLISHED", createdAt: "2026-07-08T10:15:00Z" },
  { id: "dr-010", title: "学生04 个人诊断", type: "INDIVIDUAL", targetType: "学生04", status: "ARCHIVED", createdAt: "2026-06-30T15:00:00Z" },
  { id: "dr-011", title: "高三(5)班 期中诊断", type: "CLASS", targetType: "高三(5)班", status: "PUBLISHED", createdAt: "2026-07-09T11:30:00Z" },
  { id: "dr-012", title: "学生05 个人诊断", type: "INDIVIDUAL", targetType: "学生05", status: "DRAFT", createdAt: "2026-07-10T14:00:00Z" },
];

/** 按类型 + 状态筛选诊断报告 */
export function filterDiagnosticReports(
  type?: DiagnosticReportType | null,
  status?: DiagnosticReportStatus | null,
): DiagnosticReportItem[] {
  return REPORT_DEFS.filter((r) => {
    if (type && r.type !== type) return false;
    if (status && r.status !== status) return false;
    return true;
  });
}

/** 生成班级知识点掌握度（10 知识点） */
function generateKpMastery(classId: string): DiagnosticKpMastery[] {
  const base = CLASS_BASE[classId] ?? 78;
  return KNOWLEDGE_POINTS.map((kp, i) => {
    const seed = strToSeed(`${classId}-kp-${i}`);
    const delta = Math.round((seededRandom(seed) - 0.5) * 30);
    const avg = Math.max(30, Math.min(98, base + delta));
    // 模拟 20 学生掌握度分布
    const studentCount = 20;
    const mastered = Math.round(studentCount * (avg / 100));
    const weak = Math.max(0, Math.round(studentCount * ((100 - avg) / 100) * 0.4));
    const partial = Math.max(0, studentCount - mastered - weak);
    // 中位数：基于 avg 的稳定 mock
    const med = Math.max(30, Math.min(98, avg - 2 + (i % 3) - 1));
    return {
      knowledgePoint: kp,
      avg,
      median: med,
      studentCount,
      distribution: { mastered, partial, weak },
    };
  });
}

/** 生成班级学生排名（20 学生） */
function generateRankings(classId: string): DiagnosticStudentRank[] {
  const base = CLASS_BASE[classId] ?? 78;
  const ranks: DiagnosticStudentRank[] = [];
  for (let i = 1; i <= 20; i++) {
    const seed = strToSeed(`${classId}-rank-${i}`);
    const delta = Math.round((seededRandom(seed) - 0.5) * 30);
    const masteryAvg = Math.max(30, Math.min(98, base + delta));
    ranks.push({
      rank: i,
      studentId: `stu-${classId.slice(-4)}-${String(i).padStart(3, "0")}`,
      studentName: `学生${String(i).padStart(2, "0")}`,
      masteryAvg,
    });
  }
  ranks.sort((a, b) => b.masteryAvg - a.masteryAvg);
  return ranks.map((r, i) => ({ ...r, rank: i + 1 }));
}

/** 按班级 ID 查询班级诊断 */
export function findClassDiagnostic(classId: string): ClassDiagnostic | null {
  const cls = DIAGNOSTIC_CLASSES.find((c) => c.id === classId);
  if (!cls) return null;
  const kpMastery = generateKpMastery(classId);
  // 取前 5 知识点作为顶部摘要
  const summary = kpMastery.slice(0, 5).map((k) => ({
    knowledgePoint: k.knowledgePoint,
    avg: k.avg,
  }));
  return {
    classId,
    className: cls.name,
    studentCount: 20,
    summary,
    kpMastery,
    rankings: generateRankings(classId),
  };
}

/** 5 个学生诊断 */
const STUDENT_DIAGNOSTIC_DEFS: Array<{ id: string; name: string }> = [
  { id: "stu-001", name: "学生01" },
  { id: "stu-002", name: "学生02" },
  { id: "stu-003", name: "学生03" },
  { id: "stu-004", name: "学生04" },
  { id: "stu-005", name: "学生05" },
];

/** 生成学生雷达图（6 轴） */
function generateRadar(studentId: string): DiagnosticRadarPoint[] {
  const axes = ["函数", "数列", "几何", "概率", "统计", "导数"];
  const classId = "550e8400-e29b-41d4-a716-446655440010";
  const classBase = CLASS_BASE[classId] ?? 78;
  return axes.map((axis, i) => {
    const seed = strToSeed(`${studentId}-radar-${i}`);
    const studentDelta = Math.round((seededRandom(seed) - 0.5) * 40);
    const classDelta = Math.round((seededRandom(seed + 1) - 0.5) * 10);
    return {
      axis,
      value: Math.max(20, Math.min(98, classBase + studentDelta)),
      classAvg: Math.max(40, Math.min(95, classBase + classDelta)),
    };
  });
}

/** 按学生 ID 查询学生诊断 */
export function findStudentDiagnostic(
  studentId: string,
): StudentDiagnostic | null {
  const found = STUDENT_DIAGNOSTIC_DEFS.find((s) => s.id === studentId);
  const name = found?.name ?? `学生${studentId.slice(-2)}`;
  return {
    studentId,
    studentName: name,
    radar: generateRadar(studentId),
    reports: [
      { id: `dr-${studentId}-1`, title: `${name} 期中诊断`, createdAt: "2026-07-01T09:00:00Z", status: "PUBLISHED" },
      { id: `dr-${studentId}-2`, title: `${name} 月考诊断`, createdAt: "2026-06-15T10:30:00Z", status: "ARCHIVED" },
      { id: `dr-${studentId}-3`, title: `${name} 单元诊断`, createdAt: "2026-05-20T14:00:00Z", status: "ARCHIVED" },
    ],
  };
}

/** 班级对比（5 班级 × 平均掌握度） */
export function getClassDiagnosticComparison(): Array<{
  classId: string;
  className: string;
  avgMastery: number;
}> {
  return DIAGNOSTIC_CLASSES.map((c) => {
    const base = CLASS_BASE[c.id] ?? 78;
    return { classId: c.id, className: c.name, avgMastery: base };
  });
}

/** 中位数工具导出（便于 handler 使用） */
export { median };
