/**
 * 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）：
 * - ExamBuild：按 examId 拉取试卷结构 + 题库候选列表分页
 * - SaveExamBuild：保存组卷（已选题目 + 分值 + 排序）
 * - ExamAnalytics：考后分析（分数分布/均分/最高/最低/及格率/科目对比/每题正确率/学生排名）
 * - QuestionsLibrary：题库列表（六维筛选 + 分页 + 总数）
 * - QuestionCreate / QuestionUpdate / QuestionDelete：题目 CRUD
 * - QuestionBatchImport / QuestionBatchExport：批量导入导出
 * - Textbooks：教材列表（q/subject/grade 筛选 + 分页）
 * - TextbookDetail：教材详情（章节树 + 知识点列表）
 * - TextbookCreate：创建教材
 */

import { gql } from "urql";

// ============ Types（题库） ============

/** 题目类型 */
export type QuestionType =
  | "SINGLE_CHOICE"
  | "MULTIPLE_CHOICE"
  | "TRUE_FALSE"
  | "FILL_BLANK"
  | "SHORT_ANSWER";

/** 难度等级 */
export type QuestionDifficulty = "EASY" | "MEDIUM" | "HARD";

/** 题库项 */
export interface QuestionItem {
  questionId: string;
  content: string;
  type: QuestionType;
  difficulty: QuestionDifficulty;
  textbookId: string | null;
  textbookName: string | null;
  chapterId: string | null;
  chapterName: string | null;
  kpId: string | null;
  kpName: string | null;
  score: number;
  answer: string;
  analysis: string;
  createdAt: string;
  updatedAt: string;
}

/** 题库分页结果 */
export interface QuestionsLibraryPage {
  items: QuestionItem[];
  total: number;
  page: number;
  pageSize: number;
}

/** 题库筛选条件 */
export interface QuestionsLibraryFilter {
  q?: string | null;
  type?: QuestionType | null;
  difficulty?: QuestionDifficulty | null;
  kp?: string | null;
  textbook?: string | null;
  chapter?: string | null;
  page?: number;
  pageSize?: number;
}

/** 创建题目输入 */
export interface QuestionCreateInput {
  content: string;
  type: QuestionType;
  difficulty: QuestionDifficulty;
  textbookId?: string | null;
  chapterId?: string | null;
  kpId?: string | null;
  score: number;
  answer: string;
  analysis?: string | null;
}

/** 更新题目输入 */
export interface QuestionUpdateInput {
  questionId: string;
  content?: string;
  type?: QuestionType;
  difficulty?: QuestionDifficulty;
  textbookId?: string | null;
  chapterId?: string | null;
  kpId?: string | null;
  score?: number;
  answer?: string;
  analysis?: string | null;
}

/** 批量导入项 */
export interface QuestionBatchImportItem {
  content: string;
  type: QuestionType;
  difficulty: QuestionDifficulty;
  textbookId?: string | null;
  chapterId?: string | null;
  kpId?: string | null;
  score: number;
  answer: string;
  analysis?: string | null;
}

/** 批量导入输入 */
export interface QuestionBatchImportInput {
  items: QuestionBatchImportItem[];
}

/** 批量导入结果 */
export interface QuestionBatchImportResult {
  importedCount: number;
  failedCount: number;
  errors: string[];
}

/** 批量导出结果 */
export interface QuestionBatchExportResult {
  items: QuestionItem[];
  exportedAt: string;
}

// ============ Types（教材） ============

/** 教材项（列表） */
export interface TextbookItem {
  id: string;
  title: string;
  subject: string;
  grade: string;
  version: string;
  coverUrl: string | null;
  chapterCount: number;
  createdAt: string;
}

/** 教材分页结果 */
export interface TextbooksPage {
  items: TextbookItem[];
  total: number;
  page: number;
  pageSize: number;
}

/** 教材筛选 */
export interface TextbooksFilter {
  q?: string | null;
  subject?: string | null;
  grade?: string | null;
  page?: number;
  pageSize?: number;
}

/** 教材创建输入 */
export interface TextbookCreateInput {
  title: string;
  subject: string;
  grade: string;
  version: string;
  coverUrl?: string | null;
}

/** 知识点 */
export interface KnowledgePoint {
  id: string;
  name: string;
  description: string | null;
}

/** 章节节点（含知识点） */
export interface TextbookChapter {
  id: string;
  textbookId: string;
  title: string;
  order: number;
  content: string;
  parentId: string | null;
  knowledgePoints: KnowledgePoint[];
}

/** 教材详情 */
export interface TextbookDetail {
  id: string;
  title: string;
  subject: string;
  grade: string;
  version: string;
  coverUrl: string | null;
  chapters: TextbookChapter[];
}

// ============ Types（组卷） ============

/** 已选题目（试卷节点） */
export interface ExamBuildNode {
  questionId: string;
  score: number;
  sortOrder: number;
  // 题目冗余字段（便于预览）
  content: string;
  type: QuestionType;
  difficulty: QuestionDifficulty;
}

/** 试卷结构 */
export interface ExamBuildStructure {
  examId: string;
  title: string;
  totalScore: number;
  passScore: number;
  duration: number;
  selected: ExamBuildNode[];
  // 题库候选列表（首屏分页）
  candidates: QuestionsLibraryPage;
}

/** 保存组卷输入项 */
export interface SaveExamBuildNodeInput {
  questionId: string;
  score: number;
  sortOrder: number;
}

/** 保存组卷输入 */
export interface SaveExamBuildInput {
  examId: string;
  questions: SaveExamBuildNodeInput[];
}

/** 保存组卷结果 */
export interface SaveExamBuildResult {
  examId: string;
  totalScore: number;
  questionCount: number;
  savedAt: string;
}

// ============ Types（考试分析） ============

/** 顶部统计卡片 */
export interface ExamAnalyticsSummary {
  expectedCount: number;
  attendedCount: number;
  avgScore: number;
  maxScore: number;
  minScore: number;
  passRate: number;
}

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

/** 每题正确率 */
export interface ExamQuestionAccuracy {
  questionId: string;
  questionTitle: string;
  order: number;
  correctRate: number;
  avgScore: number;
  maxScore: number;
}

/** 知识点掌握度（同 grades 模块，但语义独立） */
export interface ExamKpMastery {
  knowledgePoint: string;
  mastery: number;
}

/** 班级对比（复用 grades 类型语义，独立定义） */
export interface ExamClassComparison {
  classId: string;
  className: string;
  avg: number;
  significant: boolean;
}

/** 历次考试趋势点 */
export interface ExamHistoryTrend {
  examTitle: string;
  examDate: string;
  avg: number;
}

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

/** 考试分析完整结构 */
export interface ExamAnalytics {
  examId: string;
  examTitle: string;
  summary: ExamAnalyticsSummary;
  distribution: ExamScoreBand[];
  questionAccuracy: ExamQuestionAccuracy[];
  knowledgeMastery: ExamKpMastery[];
  classComparison: ExamClassComparison[];
  historyTrend: ExamHistoryTrend[];
  rankings: ExamStudentRank[];
}

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

/** 组卷查询（按 examId 拉取试卷结构 + 题库候选列表分页） */
export const ExamBuildQuery = gql`
  query ExamBuild(
    $examId: ID!
    $candidatePage: Int
    $candidatePageSize: Int
    $filter: QuestionsLibraryFilter
  ) {
    examBuild(
      examId: $examId
      candidatePage: $candidatePage
      candidatePageSize: $candidatePageSize
      filter: $filter
    ) {
      examId
      title
      totalScore
      passScore
      duration
      selected {
        questionId
        score
        sortOrder
        content
        type
        difficulty
      }
      candidates {
        items {
          questionId
          content
          type
          difficulty
          textbookId
          textbookName
          chapterId
          chapterName
          kpId
          kpName
          score
          answer
          analysis
          createdAt
          updatedAt
        }
        total
        page
        pageSize
      }
    }
  }
`;

/** 保存组卷 Mutation */
export const SaveExamBuildMutation = gql`
  mutation SaveExamBuild($input: SaveExamBuildInput!) {
    saveExamBuild(input: $input) {
      examId
      totalScore
      questionCount
      savedAt
    }
  }
`;

/** 考试分析查询 */
export const ExamAnalyticsQuery = gql`
  query ExamAnalytics($examId: ID!) {
    examAnalytics(examId: $examId) {
      examId
      examTitle
      summary {
        expectedCount
        attendedCount
        avgScore
        maxScore
        minScore
        passRate
      }
      distribution {
        label
        min
        max
        count
      }
      questionAccuracy {
        questionId
        questionTitle
        order
        correctRate
        avgScore
        maxScore
      }
      knowledgeMastery {
        knowledgePoint
        mastery
      }
      classComparison {
        classId
        className
        avg
        significant
      }
      historyTrend {
        examTitle
        examDate
        avg
      }
      rankings {
        rank
        studentId
        studentName
        studentNo
        totalScore
        level
      }
    }
  }
`;

/** 题库列表查询（六维筛选 + 分页 + 总数） */
export const QuestionsLibraryQuery = gql`
  query QuestionsLibrary($filter: QuestionsLibraryFilter) {
    questionsLibrary(filter: $filter) {
      items {
        questionId
        content
        type
        difficulty
        textbookId
        textbookName
        chapterId
        chapterName
        kpId
        kpName
        score
        answer
        analysis
        createdAt
        updatedAt
      }
      total
      page
      pageSize
    }
  }
`;

/** 创建题目 Mutation */
export const QuestionCreateMutation = gql`
  mutation QuestionCreate($input: QuestionCreateInput!) {
    questionCreate(input: $input) {
      questionId
      content
      type
      difficulty
      textbookId
      textbookName
      chapterId
      chapterName
      kpId
      kpName
      score
      answer
      analysis
      createdAt
      updatedAt
    }
  }
`;

/** 更新题目 Mutation */
export const QuestionUpdateMutation = gql`
  mutation QuestionUpdate($input: QuestionUpdateInput!) {
    questionUpdate(input: $input) {
      questionId
      content
      type
      difficulty
      textbookId
      textbookName
      chapterId
      chapterName
      kpId
      kpName
      score
      answer
      analysis
      createdAt
      updatedAt
    }
  }
`;

/** 删除题目 Mutation */
export const QuestionDeleteMutation = gql`
  mutation QuestionDelete($questionId: ID!) {
    questionDelete(questionId: $questionId) {
      questionId
      deleted
    }
  }
`;

/** 批量导入题目 Mutation */
export const QuestionBatchImportMutation = gql`
  mutation QuestionBatchImport($input: QuestionBatchImportInput!) {
    questionBatchImport(input: $input) {
      importedCount
      failedCount
      errors
    }
  }
`;

/** 批量导出题目查询（按当前筛选条件） */
export const QuestionBatchExportQuery = gql`
  query QuestionBatchExport($filter: QuestionsLibraryFilter) {
    questionBatchExport(filter: $filter) {
      items {
        questionId
        content
        type
        difficulty
        textbookId
        textbookName
        chapterId
        chapterName
        kpId
        kpName
        score
        answer
        analysis
        createdAt
        updatedAt
      }
      exportedAt
    }
  }
`;

/** 教材列表查询 */
export const TextbooksQuery = gql`
  query Textbooks($filter: TextbooksFilter) {
    textbooks(filter: $filter) {
      items {
        id
        title
        subject
        grade
        version
        coverUrl
        chapterCount
        createdAt
      }
      total
      page
      pageSize
    }
  }
`;

/** 教材详情查询（章节树 + 知识点列表） */
export const TextbookDetailQuery = gql`
  query TextbookDetail($id: ID!) {
    textbookDetail(id: $id) {
      id
      title
      subject
      grade
      version
      coverUrl
      chapters {
        id
        textbookId
        title
        order
        content
        parentId
        knowledgePoints {
          id
          name
          description
        }
      }
    }
  }
`;

/** 创建教材 Mutation */
export const TextbookCreateMutation = gql`
  mutation TextbookCreate($input: TextbookCreateInput!) {
    textbookCreate(input: $input) {
      id
      title
      subject
      grade
      version
      coverUrl
      chapterCount
      createdAt
    }
  }
`;
