/**
 * GraphQL operations - P7 扩展（成绩完整子模块 + 作业批改链路）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：graphql.ts P2/P3 扩展、workline.md §3 P7 交付物
 *
 * schema 尚未在 ARB-001 P2 第一版中定义，开发期通过 MSW 拦截返回 mock 响应；
 * 上游就绪后由 ai03 在 teacher-bff.graphql 扩展，届时合并本文件到 graphql.ts。
 *
 * 查询范围（P7）：
 * - GradeEntry：按 examId + classId 拉取学生成绩录入列表
 * - SaveGradeEntries：批量保存成绩录入
 * - GradeStats：班级成绩统计（avg/median/max/min/passRate/stdDev/rankings）
 * - GradeAnalytics：成绩分析（趋势/分布/学科对比/班级对比/知识点掌握度）
 * - ReportCard：学生成绩报告卡
 * - HomeworkSubmissions：按作业维度统计提交/已批数
 * - HomeworkAssignmentSubmissions：按作业 ID 拉取所有提交列表
 * - GradeSubmission：单份提交批改
 */

import { gql } from "urql";

// ============ Types（成绩录入） ============

/** 成绩录入项（单生单考试） */
export interface GradeEntryItem {
  studentId: string;
  studentName: string;
  studentNo: string;
  score: number | null;
  feedback: string | null;
}

/** 批量保存成绩录入项 */
export interface SaveGradeEntryInput {
  studentId: string;
  score: number;
  feedback?: string | null;
}

/** 批量保存成绩录入输入 */
export interface SaveGradeEntriesInput {
  examId: string;
  classId: string;
  entries: SaveGradeEntryInput[];
}

/** 批量保存结果 */
export interface SaveGradeEntriesResult {
  examId: string;
  classId: string;
  savedCount: number;
}

// ============ Types（班级成绩统计） ============

/** 班级成绩统计 */
export interface GradeStats {
  classId: string;
  className: string;
  subject: string;
  avg: number;
  median: number;
  max: number;
  min: number;
  passRate: number;
  stdDev: number;
  totalCount: number;
  rankings: GradeRanking[];
}

/** 排名项 */
export interface GradeRanking {
  rank: number;
  studentId: string;
  studentName: string;
  studentNo: string;
  totalScore: number;
  level: "A" | "B" | "C" | "D" | "E";
}

// ============ Types（成绩分析） ============

/** 成绩分析聚合 */
export interface GradeAnalytics {
  classId: string;
  className: string;
  trend: GradeTrendPoint[];
  distribution: GradeDistributionBand[];
  subjectComparison: SubjectComparisonItem[];
  classComparison: ClassComparisonItem[];
  knowledgeMastery: KnowledgeMasteryItem[];
}

/** 趋势点 */
export interface GradeTrendPoint {
  month: string;
  avg: number;
  max: number;
  min: number;
}

/** 分数分布段 */
export interface GradeDistributionBand {
  label: string;
  min: number;
  max: number;
  count: number;
}

/** 学科对比项 */
export interface SubjectComparisonItem {
  subject: string;
  avg: number;
}

/** 班级对比项 */
export interface ClassComparisonItem {
  classId: string;
  className: string;
  avg: number;
  significant: boolean;
}

/** 知识点掌握度项 */
export interface KnowledgeMasteryItem {
  knowledgePoint: string;
  mastery: number;
}

// ============ Types（报告卡） ============

/** 学生成绩报告卡 */
export interface ReportCard {
  studentId: string;
  studentName: string;
  studentNo: string;
  className: string;
  academicYear: string;
  semester: string;
  subjects: ReportCardSubject[];
  totalScore: number;
  classRank: number;
  classSize: number;
  gradeRank: number;
  gradeSize: number;
  teacherComment: string;
}

/** 报告卡科目项 */
export interface ReportCardSubject {
  subject: string;
  score: number;
  rank: number;
  teacherName: string;
}

// ============ Types（作业提交） ============

/** 作业提交统计项（按作业维度） */
export interface HomeworkSubmissionStat {
  homeworkId: string;
  title: string;
  classId: string;
  className: string;
  status: "draft" | "published" | "graded";
  dueDate: string;
  totalCount: number;
  submittedCount: number;
  gradedCount: number;
  avgScore: number | null;
}

/** 单份作业提交详情（含题目作答） */
export interface HomeworkSubmissionDetail {
  submissionId: string;
  homeworkId: string;
  homeworkTitle: string;
  classId: string;
  className: string;
  studentId: string;
  studentName: string;
  studentNo: string;
  status: "SUBMITTED" | "GRADED";
  submittedAt: string;
  totalScore: number | null;
  answers: SubmissionAnswer[];
  prevSubmissionId: string | null;
  nextSubmissionId: string | null;
}

/** 单题作答 */
export interface SubmissionAnswer {
  questionId: string;
  questionTitle: string;
  questionType: "SINGLE_CHOICE" | "MULTIPLE_CHOICE" | "SHORT_ANSWER" | "ESSAY";
  maxScore: number;
  studentAnswer: string;
  correctAnswer: string;
  score: number | null;
  feedback: string | null;
  aiSuggestion: string | null;
}

/** 单份批改输入 */
export interface GradeSubmissionInput {
  submissionId: string;
  score: number;
  feedback?: string | null;
  aiAssisted?: boolean;
  questionScores?: Array<{
    questionId: string;
    score: number;
    feedback?: string | null;
  }>;
}

/** 单份批改结果 */
export interface GradeSubmissionResult {
  submissionId: string;
  status: "GRADED";
  totalScore: number;
  feedback: string | null;
}

/** AI 批量评分建议项 */
export interface AiBatchGradingItem {
  submissionId: string;
  suggestedScore: number;
  suggestion: string;
}

// ============ Queries / Mutations ============

/** 成绩录入列表查询（按 examId + classId） */
export const GradeEntryQuery = gql`
  query GradeEntry($examId: ID!, $classId: ID!) {
    gradeEntry(examId: $examId, classId: $classId) {
      studentId
      studentName
      studentNo
      score
      feedback
    }
  }
`;

/** 批量保存成绩录入 Mutation */
export const SaveGradeEntriesMutation = gql`
  mutation SaveGradeEntries($input: SaveGradeEntriesInput!) {
    saveGradeEntries(input: $input) {
      examId
      classId
      savedCount
    }
  }
`;

/** 班级成绩统计查询 */
export const GradeStatsQuery = gql`
  query GradeStats($classId: ID!, $subject: String) {
    gradeStats(classId: $classId, subject: $subject) {
      classId
      className
      subject
      avg
      median
      max
      min
      passRate
      stdDev
      totalCount
      rankings {
        rank
        studentId
        studentName
        studentNo
        totalScore
        level
      }
    }
  }
`;

/** 成绩分析查询 */
export const GradeAnalyticsQuery = gql`
  query GradeAnalytics($classId: ID!, $semester: String, $examType: String) {
    gradeAnalytics(classId: $classId, semester: $semester, examType: $examType) {
      classId
      className
      trend {
        month
        avg
        max
        min
      }
      distribution {
        label
        min
        max
        count
      }
      subjectComparison {
        subject
        avg
      }
      classComparison {
        classId
        className
        avg
        significant
      }
      knowledgeMastery {
        knowledgePoint
        mastery
      }
    }
  }
`;

/** 学生成绩报告卡查询 */
export const ReportCardQuery = gql`
  query ReportCard($studentId: ID!, $academicYear: String, $semester: String) {
    reportCard(studentId: $studentId, academicYear: $academicYear, semester: $semester) {
      studentId
      studentName
      studentNo
      className
      academicYear
      semester
      subjects {
        subject
        score
        rank
        teacherName
      }
      totalScore
      classRank
      classSize
      gradeRank
      gradeSize
      teacherComment
    }
  }
`;

/** 作业提交统计列表查询（按作业维度） */
export const HomeworkSubmissionsQuery = gql`
  query HomeworkSubmissions($classId: ID, $status: String) {
    homeworkSubmissions(classId: $classId, status: $status) {
      homeworkId
      title
      classId
      className
      status
      dueDate
      totalCount
      submittedCount
      gradedCount
      avgScore
    }
  }
`;

/** 按作业 ID 拉取所有提交列表查询 */
export const HomeworkAssignmentSubmissionsQuery = gql`
  query HomeworkAssignmentSubmissions($homeworkId: ID!) {
    homeworkAssignmentSubmissions(homeworkId: $homeworkId) {
      submissionId
      homeworkId
      homeworkTitle
      classId
      className
      studentId
      studentName
      studentNo
      status
      submittedAt
      totalScore
      answers {
        questionId
        questionTitle
        questionType
        maxScore
        studentAnswer
        correctAnswer
        score
        feedback
        aiSuggestion
      }
      prevSubmissionId
      nextSubmissionId
    }
  }
`;

/** 单份提交批改 Mutation */
export const GradeSubmissionMutation = gql`
  mutation GradeSubmission($input: GradeSubmissionInput!) {
    gradeSubmission(input: $input) {
      submissionId
      status
      totalScore
      feedback
    }
  }
`;

/** AI 批量评分建议查询（mock：返回 AI 评分建议列表） */
export const AiBatchGradingQuery = gql`
  query AiBatchGrading($homeworkId: ID!) {
    aiBatchGrading(homeworkId: $homeworkId) {
      submissionId
      suggestedScore
      suggestion
    }
  }
`;
