import type { ActionState } from "@/shared/types/action-state"

// ---------------------------------------------------------------------------
// 基础类型
// ---------------------------------------------------------------------------

export type AiChatRole = "system" | "user" | "assistant"

export type AiChatMessage = {
  role: AiChatRole
  content: string
}

export type AiChatOptions = {
  providerId?: string
  temperature?: number
  maxTokens?: number
  model?: string
}

export type AiChatResult = {
  content: string
  usage: unknown
}

// ---------------------------------------------------------------------------
// 业务场景类型
// ---------------------------------------------------------------------------

/** 相似题推荐输入 */
export type SimilarQuestionInput = {
  questionText: string
  questionType: string
  subject?: string
  knowledgePointIds?: string[]
  count?: number
}

/** 相似题推荐结果 */
export type SimilarQuestionResult = {
  text: string
  type: string
  difficulty?: number
  options?: Array<{ id: string; text: string }>
  answer?: string
  explanation?: string
}

/** AI 辅助批改输入 */
export type GradingInput = {
  questionText: string
  questionType: string
  studentAnswer: string
  correctAnswer?: string
  maxScore: number
  subject?: string
}

/** AI 辅助批改建议 */
export type GradingSuggestion = {
  suggestedScore: number
  confidence: number
  feedback: string
  reasoning: string
}

/** 备课内容生成输入 */
export type LessonContentInput = {
  topic: string
  subject?: string
  grade?: string
  textbookId?: string
  chapterId?: string
  contentType: "activity" | "assessment" | "question" | "material"
  additionalContext?: string
}

/** 备课内容生成结果 */
export type LessonContentResult = {
  title: string
  content: string
  metadata?: Record<string, unknown>
}

/** 题目变体生成输入 */
export type QuestionVariantInput = {
  originalQuestion: {
    text: string
    type: string
    difficulty?: number
    options?: Array<{ id: string; text: string; isCorrect?: boolean }>
    answer?: string
  }
  subject?: string
  variantType: "same_knowledge_point" | "different_difficulty" | "different_format"
}

/** 题目变体生成结果 */
export type QuestionVariantResult = {
  text: string
  type: string
  difficulty: number
  options?: Array<{ id: string; text: string; isCorrect: boolean }>
  answer?: string
  explanation?: string
}

/** 薄弱点分析输入 */
export type WeaknessAnalysisInput = {
  studentId: string
  subjectId?: string
  errorItems: Array<{
    questionText: string
    questionType: string
    knowledgePointIds?: string[]
    errorCount: number
    masteryLevel: number
  }>
}

/** 薄弱点分析结果 */
export type WeaknessAnalysisResult = {
  weakAreas: Array<{
    area: string
    severity: "high" | "medium" | "low"
    suggestion: string
  }>
  studyPlan: string
  recommendedResources: string[]
}

/** 家长学情摘要输入 */
export type ChildSummaryInput = {
  studentId: string
  studentName?: string
  grade?: string
  recentGrades?: Array<{
    subject: string
    score: number
    maxScore: number
    trend: "up" | "down" | "stable"
  }>
  attendanceRate?: number
  errorBookSummary?: {
    totalErrors: number
    topWeakSubjects: string[]
    masteryTrend: "improving" | "declining" | "stable"
  }
  homeworkCompletionRate?: number
}

/** 家长学情摘要结果 */
export type ChildSummaryResult = {
  overallAssessment: string
  strengths: string[]
  areasForImprovement: string[]
  familyTutoringSuggestions: string[]
  nextSteps: string[]
}

/** 学习路径推荐输入 */
export type StudyPathInput = {
  studentId: string
  subject?: string
  currentMastery?: Array<{
    knowledgePoint: string
    masteryLevel: number
    errorCount: number
  }>
  learningGoal?: string
  /** 教材 ID（传入后 action 层自动获取知识图谱注入） */
  textbookId?: string
  /**
   * 知识图谱上下文（V3 新增，对标 Squirrel AI 纳米级知识图谱）
   *
   * 由 actions 层从 textbooks/data-access-graph 获取后注入，
   * 使 AI 能沿前置依赖链推荐学习路径。
   */
  knowledgeGraph?: {
    nodes: Array<{
      id: string
      name: string
      level: number
      masteryLevel?: number
    }>
    edges: Array<{ from: string; to: string; type: "prerequisite" }>
  }
}

/** 学习路径推荐结果 */
export type StudyPathResult = {
  currentLevel: string
  learningPath: Array<{
    step: number
    knowledgePoint: string
    status: "mastered" | "in_progress" | "needs_work"
    recommendedAction: string
    estimatedTime: string
  }>
  summary: string
  motivation: string
}

/** AI 使用统计（管理员） */
export type AiUsageStats = {
  totalCalls: number
  callsToday: number
  callsThisWeek: number
  activeUsers: number
  errorRate: number
  avgDurationMs: number
  byCapability: Array<{ capability: string; count: number }>
  byRole: Array<{ role: string; count: number }>
  topUsers: Array<{ userId: string; count: number }>
  recentActivity: Array<{
    userId: string
    capability: string
    success: boolean
    durationMs: number
    timestamp: string
  }>
}

/** 错题 AI 解释输入 */
export type ExplainErrorInput = {
  /** 题目文本 */
  questionText: string
  /** 题目类型 */
  questionType: string
  /** 学生错误答案 */
  studentAnswer: string
  /** 正确答案 */
  correctAnswer?: string
  /** 学科 */
  subject?: string
  /** 知识点 ID 列表 */
  knowledgePointIds?: string[]
}

/** 错题 AI 解释结果 */
export type ExplainErrorResult = {
  /** 错误原因分析 */
  errorAnalysis: string
  /** 正确解题思路 */
  correctApproach: string
  /** 关键知识点 */
  keyConcepts: string[]
  /** 类似错误防范建议 */
  preventionTips: string[]
  /** 练习建议 */
  practiceSuggestion: string
}

// ---------------------------------------------------------------------------
// AI 能力配置（角色驱动）
// ---------------------------------------------------------------------------

export type AiCapability =
  | "chat"
  | "exam-generate"
  | "grading-assist"
  | "lesson-content"
  | "question-variant"
  | "similar-question"
  | "weakness-analysis"
  | "study-path"
  | "child-summary"
  | "usage-stats"
  | "explain-error"

// ---------------------------------------------------------------------------
// 服务接口
// ---------------------------------------------------------------------------

/**
 * AI 服务接口（服务端）
 *
 * 业务模块的 data-access 或 actions 通过此接口调用 AI 能力，
 * 不直接 import shared/lib/ai。
 * 测试时可注入 mock 实现。
 */
export interface AiService {
  chat(messages: AiChatMessage[], options?: AiChatOptions): Promise<AiChatResult>
  suggestSimilarQuestions(input: SimilarQuestionInput): Promise<SimilarQuestionResult[]>
  suggestGrading(input: GradingInput): Promise<GradingSuggestion>
  generateLessonContent(input: LessonContentInput): Promise<LessonContentResult>
  generateQuestionVariant(input: QuestionVariantInput): Promise<QuestionVariantResult>
  analyzeWeakness(input: WeaknessAnalysisInput): Promise<WeaknessAnalysisResult>
  generateChildSummary(input: ChildSummaryInput): Promise<ChildSummaryResult>
  recommendStudyPath(input: StudyPathInput): Promise<StudyPathResult>
  explainError(input: ExplainErrorInput): Promise<ExplainErrorResult>
}

/**
 * AI 客户端服务接口
 *
 * 注入 Server Action 引用，客户端组件通过此接口触发 AI 操作。
 * 遵循 settings 模块的依赖注入模式。
 */
export interface AiClientService {
  chat: (input: {
    messages: AiChatMessage[]
    providerId?: string
  }) => Promise<ActionState<AiChatResult>>
  suggestSimilarQuestions: (
    input: SimilarQuestionInput
  ) => Promise<ActionState<SimilarQuestionResult[]>>
  suggestGrading: (input: GradingInput) => Promise<ActionState<GradingSuggestion>>
  generateLessonContent: (
    input: LessonContentInput
  ) => Promise<ActionState<LessonContentResult>>
  generateQuestionVariant: (
    input: QuestionVariantInput
  ) => Promise<ActionState<QuestionVariantResult>>
  analyzeWeakness: (
    input: WeaknessAnalysisInput
  ) => Promise<ActionState<WeaknessAnalysisResult>>
  generateChildSummary?: (
    input: ChildSummaryInput
  ) => Promise<ActionState<ChildSummaryResult>>
  recommendStudyPath?: (
    input: StudyPathInput
  ) => Promise<ActionState<StudyPathResult>>
  getAiUsageStats?: () => Promise<ActionState<AiUsageStats>>
  explainError?: (
    input: ExplainErrorInput
  ) => Promise<ActionState<ExplainErrorResult>>
  /** 预留埋点接口 */
  trackEvent?: (event: string, payload?: Record<string, unknown>) => void
}
