/**
 * 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-insights）：
 * - LessonPlans / LessonPlanDetail / LessonPlanLibrary / LessonPlanCalendar / LessonPlanHeatmap
 * - CreateLessonPlan / UpdateLessonPlan / AIGenerateLessonPlan / ForkLessonPlan
 * - CoursePlans / CoursePlanDetail / CreateCoursePlan / UpdateCoursePlan
 * - DiagnosticReports / ClassDiagnostic / StudentDiagnostic
 * - ErrorBook（错题分析聚合）
 * - PracticeAnalytics（自适应练习分析聚合）
 */

import { gql } from "urql";

// ============ Types（课案） ============

export type LessonPlanStatus = "DRAFT" | "PUBLISHED" | "ARCHIVED";

export type LessonPlanTemplate =
  | "REGULAR"
  | "UNIT"
  | "REVIEW"
  | "ACTIVITY"
  | "PERSONALIZED";

export interface LessonPlanAIHistoryItem {
  id: string;
  prompt: string;
  generatedAt: string;
  model: string;
}

export interface LessonPlanItem {
  id: string;
  title: string;
  subject: string;
  grade: string;
  chapter: string;
  status: LessonPlanStatus;
  textbookId: string | null;
  textbookTitle: string | null;
  classIds: string[];
  updatedAt: string;
}

export interface LessonPlanDetail {
  id: string;
  title: string;
  subject: string;
  grade: string;
  chapter: string;
  content: string;
  status: LessonPlanStatus;
  textbookId: string | null;
  textbookTitle: string | null;
  classIds: string[];
  aiHistory: LessonPlanAIHistoryItem[];
  updatedAt: string;
  createdAt: string;
}

export interface LessonPlanLibraryItem {
  id: string;
  title: string;
  author: string;
  subject: string;
  grade: string;
  chapter: string;
  rating: number;
  forkCount: number;
  updatedAt: string;
}

export interface LessonPlanCalendarDay {
  date: string;
  planCount: number;
  planTitles: string[];
}

export interface LessonPlanCalendarMonth {
  year: number;
  month: number;
  days: LessonPlanCalendarDay[];
}

export interface LessonPlanHeatmapCell {
  textbookKp: string;
  planIds: string[];
  covered: boolean;
}

export interface LessonPlanHeatmap {
  rows: string[];
  cols: string[];
  cells: LessonPlanHeatmapCell[];
}

export interface CreateLessonPlanInput {
  title: string;
  subject: string;
  grade: string;
  chapter: string;
  textbookId?: string | null;
  template: LessonPlanTemplate;
}

export interface UpdateLessonPlanInput {
  planId: string;
  title?: string;
  content?: string;
  status?: LessonPlanStatus;
  textbookId?: string | null;
  chapter?: string;
  classIds?: string[];
}

export interface AIGenerateLessonPlanInput {
  subject: string;
  grade: string;
  chapter: string;
  prompt: string;
}

export interface AIGenerateLessonPlanResult {
  id: string;
  content: string;
  summary: string;
  model: string;
  generatedAt: string;
}

// ============ Types（课程计划） ============

export type CoursePlanStatus = "DRAFT" | "PUBLISHED" | "ARCHIVED";

export interface CoursePlanChapter {
  id: string;
  title: string;
  hours: number;
  objectives: string;
  keyPoints: string;
  activities: string;
}

export interface CoursePlanItem {
  id: string;
  title: string;
  subject: string;
  grade: string;
  academicYear: string;
  semester: string;
  totalHours: number;
  status: CoursePlanStatus;
  textbookId: string | null;
  updatedAt: string;
}

export interface CoursePlanDetail {
  id: string;
  title: string;
  subject: string;
  grade: string;
  academicYear: string;
  semester: string;
  totalHours: number;
  status: CoursePlanStatus;
  textbookId: string | null;
  textbookTitle: string | null;
  homeworkCount: number;
  chapters: CoursePlanChapter[];
  updatedAt: string;
}

export interface CreateCoursePlanInput {
  title: string;
  subject: string;
  grade: string;
  academicYear: string;
  semester: string;
  totalHours: number;
  textbookId?: string | null;
}

export interface UpdateCoursePlanInput {
  id: string;
  title?: string;
  status?: CoursePlanStatus;
  chapters?: CoursePlanChapter[];
}

// ============ Types（诊断） ============

export type DiagnosticReportType = "INDIVIDUAL" | "CLASS" | "GRADE";
export type DiagnosticReportStatus = "DRAFT" | "PUBLISHED" | "ARCHIVED";

export interface DiagnosticReportItem {
  id: string;
  title: string;
  type: DiagnosticReportType;
  targetType: string;
  status: DiagnosticReportStatus;
  createdAt: string;
}

export interface DiagnosticKpMastery {
  knowledgePoint: string;
  avg: number;
  median: number;
  studentCount: number;
  distribution: { mastered: number; partial: number; weak: number };
}

export interface DiagnosticStudentRank {
  rank: number;
  studentId: string;
  studentName: string;
  masteryAvg: number;
}

export interface ClassDiagnostic {
  classId: string;
  className: string;
  studentCount: number;
  summary: { knowledgePoint: string; avg: number }[];
  kpMastery: DiagnosticKpMastery[];
  rankings: DiagnosticStudentRank[];
}

export interface DiagnosticRadarPoint {
  axis: string;
  value: number;
  classAvg: number;
}

export interface StudentDiagnostic {
  studentId: string;
  studentName: string;
  radar: DiagnosticRadarPoint[];
  reports: { id: string; title: string; createdAt: string; status: DiagnosticReportStatus }[];
}

// ============ Types（错题本） ============

export interface ErrorBookSummary {
  totalErrors: number;
  highFreqErrors: number;
  weakKpCount: number;
  avgErrorRate: number;
  trendUp: boolean;
}

export interface ErrorBookClassComparison {
  classId: string;
  className: string;
  errorCount: number;
}

export interface ErrorBookChapterWeakness {
  chapter: string;
  errorCount: number;
}

export interface ErrorBookKpWeakness {
  knowledgePoint: string;
  errorRate: number;
}

export interface ErrorBookStudentGroup {
  studentId: string;
  studentName: string;
  errorCount: number;
  topErrors: { questionId: string; content: string; errorRate: number }[];
}

export interface ErrorBookTopQuestion {
  questionId: string;
  content: string;
  errorRate: number;
  subject: string;
}

export interface ErrorBook {
  subject: string;
  classId: string;
  summary: ErrorBookSummary;
  classComparison: ErrorBookClassComparison[];
  chapterWeakness: ErrorBookChapterWeakness[];
  kpWeakness: ErrorBookKpWeakness[];
  studentGroups: ErrorBookStudentGroup[];
  topQuestions: ErrorBookTopQuestion[];
}

// ============ Types（练习） ============

export interface PracticeSummary {
  totalSessions: number;
  completionRate: number;
  avgAccuracy: number;
  weakKpCount: number;
  participationRate: number;
}

export interface PracticeClassComparison {
  classId: string;
  className: string;
  totalSessions: number;
  completionRate: number;
  avgAccuracy: number;
  participationRate: number;
  weakKpCount: number;
}

export interface PracticeTypeBreakdown {
  type: string;
  count: number;
  ratio: number;
}

export interface PracticeKpWeakness {
  knowledgePoint: string;
  accuracy: number;
}

export interface PracticeStudentRank {
  rank: number;
  studentId: string;
  studentName: string;
  studentNo: string;
  totalSessions: number;
  accuracy: number;
  weakKp: string;
}

export interface PracticeInactiveStudent {
  studentId: string;
  studentName: string;
  lastActiveDays: number;
}

export interface PracticeAnalytics {
  classId: string;
  summary: PracticeSummary;
  classComparison: PracticeClassComparison[];
  typeBreakdown: PracticeTypeBreakdown[];
  kpWeakness: PracticeKpWeakness[];
  rankings: PracticeStudentRank[];
  inactiveStudents: PracticeInactiveStudent[];
}

// ============ Queries / Mutations（课案） ============

export const LessonPlansQuery = gql`
  query LessonPlans($subject: String) {
    lessonPlans(subject: $subject) {
      id
      title
      subject
      grade
      chapter
      status
      textbookId
      textbookTitle
      classIds
      updatedAt
    }
  }
`;

export const LessonPlanDetailQuery = gql`
  query LessonPlanDetail($planId: ID!) {
    lessonPlanDetail(planId: $planId) {
      id
      title
      subject
      grade
      chapter
      content
      status
      textbookId
      textbookTitle
      classIds
      aiHistory {
        id
        prompt
        generatedAt
        model
      }
      updatedAt
      createdAt
    }
  }
`;

export const CreateLessonPlanMutation = gql`
  mutation CreateLessonPlan($input: CreateLessonPlanInput!) {
    createLessonPlan(input: $input) {
      id
      title
      subject
      grade
      chapter
      status
      textbookId
      textbookTitle
      classIds
      updatedAt
    }
  }
`;

export const UpdateLessonPlanMutation = gql`
  mutation UpdateLessonPlan($input: UpdateLessonPlanInput!) {
    updateLessonPlan(input: $input) {
      id
      title
      content
      status
      textbookId
      chapter
      classIds
      updatedAt
    }
  }
`;

export const AIGenerateLessonPlanMutation = gql`
  mutation AIGenerateLessonPlan($input: AIGenerateLessonPlanInput!) {
    aiGenerateLessonPlan(input: $input) {
      id
      content
      summary
      model
      generatedAt
    }
  }
`;

export const LessonPlanLibraryQuery = gql`
  query LessonPlanLibrary($subject: String, $grade: String) {
    lessonPlanLibrary(subject: $subject, grade: $grade) {
      id
      title
      author
      subject
      grade
      chapter
      rating
      forkCount
      updatedAt
    }
  }
`;

export const ForkLessonPlanMutation = gql`
  mutation ForkLessonPlan($planId: ID!) {
    forkLessonPlan(planId: $planId) {
      id
      title
      subject
      grade
      chapter
      status
      textbookId
      textbookTitle
      classIds
      updatedAt
    }
  }
`;

export const LessonPlanCalendarQuery = gql`
  query LessonPlanCalendar($year: Int!, $month: Int!) {
    lessonPlanCalendar(year: $year, month: $month) {
      year
      month
      days {
        date
        planCount
        planTitles
      }
    }
  }
`;

export const LessonPlanHeatmapQuery = gql`
  query LessonPlanHeatmap {
    lessonPlanHeatmap {
      rows
      cols
      cells {
        textbookKp
        planIds
        covered
      }
    }
  }
`;

// ============ Queries / Mutations（课程计划） ============

export const CoursePlansQuery = gql`
  query CoursePlans($status: CoursePlanStatus) {
    coursePlans(status: $status) {
      id
      title
      subject
      grade
      academicYear
      semester
      totalHours
      status
      textbookId
      updatedAt
    }
  }
`;

export const CoursePlanDetailQuery = gql`
  query CoursePlanDetail($id: ID!) {
    coursePlanDetail(id: $id) {
      id
      title
      subject
      grade
      academicYear
      semester
      totalHours
      status
      textbookId
      textbookTitle
      homeworkCount
      chapters {
        id
        title
        hours
        objectives
        keyPoints
        activities
      }
      updatedAt
    }
  }
`;

export const CreateCoursePlanMutation = gql`
  mutation CreateCoursePlan($input: CreateCoursePlanInput!) {
    createCoursePlan(input: $input) {
      id
      title
      subject
      grade
      academicYear
      semester
      totalHours
      status
      textbookId
      updatedAt
    }
  }
`;

export const UpdateCoursePlanMutation = gql`
  mutation UpdateCoursePlan($input: UpdateCoursePlanInput!) {
    updateCoursePlan(input: $input) {
      id
      title
      status
      updatedAt
    }
  }
`;

// ============ Queries（诊断） ============

export const DiagnosticReportsQuery = gql`
  query DiagnosticReports($type: DiagnosticReportType, $status: DiagnosticReportStatus) {
    diagnosticReports(type: $type, status: $status) {
      id
      title
      type
      targetType
      status
      createdAt
    }
  }
`;

export const ClassDiagnosticQuery = gql`
  query ClassDiagnostic($classId: ID!) {
    classDiagnostic(classId: $classId) {
      classId
      className
      studentCount
      summary {
        knowledgePoint
        avg
      }
      kpMastery {
        knowledgePoint
        avg
        median
        studentCount
        distribution {
          mastered
          partial
          weak
        }
      }
      rankings {
        rank
        studentId
        studentName
        masteryAvg
      }
    }
  }
`;

export const StudentDiagnosticQuery = gql`
  query StudentDiagnostic($studentId: ID!) {
    studentDiagnostic(studentId: $studentId) {
      studentId
      studentName
      radar {
        axis
        value
        classAvg
      }
      reports {
        id
        title
        createdAt
        status
      }
    }
  }
`;

// ============ Queries（错题本 / 练习） ============

export const ErrorBookQuery = gql`
  query ErrorBook($subject: String!, $classId: String) {
    errorBook(subject: $subject, classId: $classId) {
      subject
      classId
      summary {
        totalErrors
        highFreqErrors
        weakKpCount
        avgErrorRate
        trendUp
      }
      classComparison {
        classId
        className
        errorCount
      }
      chapterWeakness {
        chapter
        errorCount
      }
      kpWeakness {
        knowledgePoint
        errorRate
      }
      studentGroups {
        studentId
        studentName
        errorCount
        topErrors {
          questionId
          content
          errorRate
        }
      }
      topQuestions {
        questionId
        content
        errorRate
        subject
      }
    }
  }
`;

export const PracticeAnalyticsQuery = gql`
  query PracticeAnalytics($classId: String) {
    practiceAnalytics(classId: $classId) {
      classId
      summary {
        totalSessions
        completionRate
        avgAccuracy
        weakKpCount
        participationRate
      }
      classComparison {
        classId
        className
        totalSessions
        completionRate
        avgAccuracy
        participationRate
        weakKpCount
      }
      typeBreakdown {
        type
        count
        ratio
      }
      kpWeakness {
        knowledgePoint
        accuracy
      }
      rankings {
        rank
        studentId
        studentName
        studentNo
        totalSessions
        accuracy
        weakKp
      }
      inactiveStudents {
        studentId
        studentName
        lastActiveDays
      }
    }
  }
`;
