// parent-portal 类型定义
// 依据：02-architecture-design.md §2 领域模型、§14 通知偏好数据模型、§15 详细组件设计

// ===== 会话状态（Session）=====
export interface UserSession {
  id: string;
  email: string;
  name: string;
  roles: string[];
  permissions: string[];
  dataScope: DataScope;
  schoolId?: string;
}

export type DataScope =
  | "ALL"
  | "SCHOOL"
  | "GRADE"
  | "CLASS"
  | "SUBJECT"
  | "CHILDREN" // 家长特有：仅自己绑定的子女
  | "SELF";

// ===== 视口（Viewport）=====
export interface ViewportItem {
  key: string;
  label: string;
  route: string;
  icon: string | null;
  sortOrder: string;
  requiredPermission: string | null;
  scope: "parent";
}

// ===== 子女信息（ChildInfo）=====
export interface ChildInfo {
  id: string;
  name: string;
  avatar?: string;
  grade: string; // i18n key
  schoolName: string;
  classId: string;
  className?: string;
  isArchived?: boolean; // 已归档（转学/离校）
}

// ===== 子女仪表盘概览（childSummary）=====
export interface ChildSummary {
  childId: string;
  avgScore: number;
  classRank: number;
  classSize: number;
  attendanceRate: number; // 0-1
  pendingHomeworkCount: number;
  recentGradeTrend: "up" | "down" | "stable";
  recentScores: GradeDataPoint[];
  upcomingEvents?: UpcomingEvent[];
}

export interface UpcomingEvent {
  id: string;
  type: "exam" | "homework" | "activity";
  title: string;
  dueDate: string; // ISO 8601
}

// ===== 成绩（Grade）=====
export interface GradeDataPoint {
  examId: string;
  examName: string;
  examDate: string; // ISO 8601
  subject: string;
  studentScore: number;
  classAverage?: number;
  classMax?: number;
  classMin?: number;
  gradeLevel: "A" | "B" | "C" | "D" | "F";
}

// ===== 考勤（Attendance）=====
export interface AttendanceRecord {
  id: string;
  date: string; // ISO 8601 date
  status: "present" | "absent" | "late" | "leave";
  note?: string;
}

// ===== 作业（Homework）=====
export interface HomeworkItem {
  id: string;
  title: string;
  subject: string;
  className: string;
  assignedDate: string; // ISO 8601
  dueDate: string; // ISO 8601
  status: "not_started" | "in_progress" | "submitted" | "graded";
  score?: number;
  maxScore: number;
  feedback?: string;
}

// ===== 学情分析 =====
export interface WeaknessPoint {
  id: string;
  knowledgePoint: string;
  masteryLevel: number; // 0-1
  subject: string;
  recommendation?: string;
}

export interface LearningTrend {
  childId: string;
  period: "week" | "month" | "semester";
  dataPoints: TrendDataPoint[];
}

export interface TrendDataPoint {
  date: string;
  score: number;
  subject?: string;
}

// ===== 考试（子女视角，只读）=====
export type ExamStatus =
  "not_started" | "in_progress" | "submitted" | "graded" | "expired";

export interface ExamListItem {
  id: string;
  name: string;
  subject: string;
  status: ExamStatus;
  startsAt: string; // ISO 8601
  expiresAt: string; // ISO 8601
  durationSeconds: number;
  questionCount: number;
  totalScore: number;
  /** 已提交时携带 */
  submittedAt?: string;
}

// ===== 考试结果（逐题回顾）=====
export type QuestionType =
  "single-choice" | "multiple-choice" | "fill-blank" | "short-answer" | "essay";

export type AnswerInput =
  | { type: "single-choice"; optionId: string }
  | { type: "multiple-choice"; optionIds: string[] }
  | { type: "fill-blank"; values: string[] }
  | { type: "short-answer"; text: string }
  | { type: "essay"; text: string };

export interface QuestionResult {
  questionId: string;
  questionContent: string;
  questionType: QuestionType;
  studentAnswer: AnswerInput | null;
  correctAnswer: AnswerInput | null;
  isCorrect: boolean;
  isAnswered: boolean;
  explanation?: string;
  maxScore: number;
  earnedScore: number;
}

export interface ExamResultSummary {
  totalQuestions: number;
  correctCount: number;
  wrongCount: number;
  unansweredCount: number;
}

export interface ExamResult {
  examId: string;
  examName: string;
  score: number;
  maxScore: number;
  grade: string;
  submittedAt: string; // ISO 8601
  durationSeconds: number;
  questionResults: QuestionResult[];
}

// ===== 班级信息（子女所在班级）=====
export interface ClassInfo {
  id: string;
  name: string;
  homeroomTeacher: string;
  studentCount: number;
  grade: string;
  year: number;
}

// ===== 学习路径（子女知识点掌握）=====
export type NodeStatus = "locked" | "available" | "in-progress" | "completed";

export interface LearningPathNode {
  id: string;
  name: string;
  knowledgePointId: string;
  status: NodeStatus;
  mastery: number; // 0-1
  dependencies: string[];
  recommendedOrder: number;
  recommendation?: string;
}

// ===== 通知 =====
export interface NotificationItem {
  id: string;
  childId: string | null;
  eventType: NotificationEventType;
  title: string; // i18n key
  body: string; // i18n key + 参数
  read: boolean;
  createdAt: string; // ISO 8601
  actionUrl?: string;
  pinned?: boolean;
}

// ===== 通知偏好（02 §14 通知偏好数据模型）=====
export type NotificationEventType =
  | "grade_recorded"
  | "homework_graded"
  | "homework_assigned"
  | "exam_published"
  | "attendance_alert"
  | "school_announcement"
  | "teacher_message"
  | "fee_reminder"
  | "event_invitation";

export type NotificationChannel =
  "in_app" | "push" | "sms" | "email" | "wechat";

export interface NotificationPreferences {
  parentId: string;
  // 三维矩阵：children[eventType][channel] = enabled
  // Partial 内层：允许部分 eventType 未设置（新增子女时不必预填全部事件）
  preferences: Record<
    string, // childId（"*" 表示全部子女）
    Partial<
      Record<
        NotificationEventType,
        Partial<Record<NotificationChannel, boolean>>
      >
    >
  >;
  // 全局默认
  defaults: Record<
    NotificationEventType,
    Partial<Record<NotificationChannel, boolean>>
  >;
  updatedAt: string; // ISO 8601
}

export interface AvailableChannels {
  in_app: boolean;
  push: boolean;
  sms: boolean;
  email: boolean;
  wechat: boolean;
}

// ===== API 错误 =====
export interface ApiError {
  code: string;
  message: string;
  details?: unknown;
  traceId?: string;
}

// ===== ActionState（统一响应契约）=====
export type ActionState<T> =
  { success: true; data: T } | { success: false; error: ApiError };

// ===== 登录响应 =====
export interface LoginResponse {
  user: UserSession;
  tokens: {
    accessToken: string;
    refreshToken: string;
    expiresIn: number;
  };
}

// ===== WebSocket 推送事件（P5）=====
export type WebSocketEvent =
  | {
      type: "NotificationRequested";
      notification: NotificationItem;
    }
  | {
      type: "GradeRecorded";
      childId: string;
      examId: string;
      examName: string;
      score: number;
    }
  | {
      type: "SchoolAnnouncement";
      title: string;
      body: string;
    }
  | {
      type: "ChildUnbound";
      childId: string;
    }
  | {
      type: "ChildBound";
      child: ChildInfo;
    };

// ===== 跨标签同步消息 =====
export type SyncMessage =
  | {
      type: "child-switched";
      childId: string;
      ts: number;
      source: string;
    }
  | {
      type: "child-unbound";
      childId: string;
      ts: number;
      source: string;
    }
  | {
      type: "preferences-updated";
      ts: number;
      source: string;
    };

// ===== 请假（Leave，参考项目 /parent/leave）=====
export type LeaveType = "sick" | "personal" | "family" | "other";
export type LeaveStatus = "pending" | "approved" | "rejected" | "cancelled";

export interface LeaveRequest {
  id: string;
  childId: string;
  childName?: string;
  className?: string;
  type: LeaveType;
  startDate: string; // ISO 8601 date
  endDate: string; // ISO 8601 date
  reason: string;
  status: LeaveStatus;
  submittedAt: string; // ISO 8601
  reviewedAt?: string;
  reviewerName?: string;
  reviewComment?: string;
}

export interface LeaveRequestInput {
  childId: string;
  type: LeaveType;
  startDate: string;
  endDate: string;
  reason: string;
}

// ===== 报告卡（ReportCard，参考项目 /parent/grades/report-card）=====
export interface AcademicYear {
  id: string;
  name: string; // 如 "2025-2026"
  startDate: string;
  endDate: string;
}

export interface ReportCard {
  childId: string;
  childName: string;
  className: string;
  academicYearId: string;
  academicYearName: string;
  semester: 1 | 2;
  subjects: ReportCardSubject[];
  overallScore: number;
  classRank: number;
  classSize: number;
  teacherComment: string;
  headTeacherComment?: string;
  issuedAt: string;
}

export interface ReportCardSubject {
  subject: string;
  score: number;
  maxScore: number;
  gradeLevel: "A" | "B" | "C" | "D" | "F";
  classAverage: number;
  rank: number;
  classSize: number;
  teacherComment?: string;
}

// ===== 错题本（ErrorBook，参考项目 /parent/error-book）=====
export interface ErrorBookStats {
  childId: string;
  totalCount: number;
  newCount: number;
  learningCount: number;
  masteredCount: number;
  dueReviewCount: number;
  masteredRate: number; // 0-1
}

export interface TopWrongQuestion {
  id: string;
  questionContent: string;
  subject: string;
  knowledgePoint: string;
  errorCount: number;
  lastErrorAt: string;
  masteryRate: number; // 0-1
}

export interface WeakKp {
  knowledgePointName: string;
  subject: string;
  errorCount: number;
  masteryRate: number; // 0-1
}

// ===== 诊断报告（Diagnostic，参考项目 /parent/diagnostic）=====
export type DiagnosticReportStatus = "draft" | "published" | "archived";

export interface DiagnosticReport {
  id: string;
  childId: string;
  title: string;
  summary: string;
  status: DiagnosticReportStatus;
  createdAt: string;
  publishedAt?: string;
  masteryScore: number; // 0-100
  subjects: DiagnosticSubject[];
}

export interface DiagnosticSubject {
  subject: string;
  masteryLevel: number; // 0-1
  strengths: string[];
  weaknesses: string[];
  recommendation: string;
}

export interface MasterySummary {
  childId: string;
  overallMastery: number; // 0-1
  subjectMastery: { subject: string; mastery: number }[];
  totalKps: number;
  masteredKps: number;
}

// ===== 练习统计（Practice，参考项目 /parent/practice）=====
export interface PracticeStats {
  childId: string;
  totalSessions: number;
  completedSessions: number;
  totalQuestionsAnswered: number;
  overallAccuracy: number; // 0-1
}

export interface PracticeSession {
  id: string;
  childId: string;
  subject: string;
  startedAt: string;
  completedAt?: string;
  questionCount: number;
  correctCount: number;
  accuracy: number; // 0-1
  durationSeconds: number;
  knowledgePoints: string[];
}

// ===== 课程计划（CoursePlan，参考项目 /parent/course-plans）=====
export interface CoursePlan {
  id: string;
  title: string;
  description: string;
  subject: string;
  className: string;
  teacherName: string;
  startDate: string;
  endDate: string;
  status: "active" | "completed" | "archived";
  chapterCount: number;
}

export interface CoursePlanDetail extends CoursePlan {
  chapters: CoursePlanChapter[];
}

export interface CoursePlanChapter {
  id: string;
  title: string;
  description: string;
  sortOrder: number;
  lessonCount: number;
  estimatedHours: number;
}

// ===== 备课计划（LessonPlan，参考项目 /parent/lesson-plans）=====
export interface LessonPlan {
  id: string;
  title: string;
  subject: string;
  className: string;
  teacherName: string;
  textbookTitle: string;
  chapterTitle: string;
  status: "draft" | "published" | "archived";
  publishedAt?: string;
  estimatedMinutes: number;
}

export interface LessonPlanDetail extends LessonPlan {
  objectives: string[];
  keyPoints: string[];
  difficultPoints: string[];
  content: string;
  homeworkDescription?: string;
}

// ===== 选修课（Elective，参考项目 /parent/elective）=====
export interface ElectiveSelection {
  id: string;
  childId: string;
  courseName: string;
  courseCode: string;
  teacherName: string;
  category: "arts" | "science" | "sports" | "language" | "other";
  credits: number;
  schedule: string; // 如 "周三 15:00-16:30"
  status: "enrolled" | "completed" | "dropped";
  enrolledAt: string;
  score?: number;
}

// ===== 子女详情聚合（ChildDetail，参考项目 /parent/children/[studentId]）=====
export interface ChildDetail {
  childId: string;
  basicInfo: {
    name: string;
    avatar?: string;
    grade: string;
    className: string;
    schoolName: string;
    relation: string; // 如 "父亲" / "母亲"
  };
  todaySchedule: ScheduleItem[];
  weeklySchedule: ScheduleItem[];
  homeworkSummary: {
    pendingCount: number;
    overdueCount: number;
    submittedCount: number;
    gradedCount: number;
  };
  gradeSummary: {
    avgScore: number;
    classRank: number;
    classSize: number;
    trend: "up" | "down" | "stable";
  };
  examResults: {
    upcoming: number;
    completed: number;
    avgScore: number;
  };
}

export interface ScheduleItem {
  id: string;
  dayOfWeek: number; // 0-6 (0=周日)
  period: number; // 第几节课
  subject: string;
  teacherName: string;
  classroom: string;
  startTime: string; // HH:mm
  endTime: string; // HH:mm
}

// ===== 导出请求 =====
export interface ExportResult {
  downloadUrl: string;
  expiresAt: string;
}

// ===== 成长档案（班级均对比线）=====
export interface GrowthArchiveDataPoint {
  date: string; // YYYY-MM 格式
  studentScore: number;
  classAverage: number;
}

export interface GrowthArchive {
  childId: string;
  subject: string;
  dataPoints: GrowthArchiveDataPoint[];
}
