"use server"

import { getTranslations } from "next-intl/server"

import type { ActionState } from "@/shared/types/action-state"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions, type Permission } from "@/shared/types/permissions"

import { createAiService, safeAiCall } from "./services/ai-service"
import { getAiUsageStats } from "./data-access"
import { getKnowledgePointsWithRelations, getStudentKpMastery } from "@/modules/textbooks/data-access-graph"
import {
  AiChatInputSchema,
  GradingInputSchema,
  LessonContentInputSchema,
  QuestionVariantInputSchema,
  SimilarQuestionInputSchema,
  WeaknessAnalysisInputSchema,
  ChildSummaryInputSchema,
  StudyPathInputSchema,
  ExplainErrorInputSchema,
} from "./schema"
import type {
  AiChatMessage,
  AiChatResult,
  GradingInput,
  GradingSuggestion,
  LessonContentInput,
  LessonContentResult,
  QuestionVariantInput,
  QuestionVariantResult,
  SimilarQuestionInput,
  SimilarQuestionResult,
  WeaknessAnalysisInput,
  WeaknessAnalysisResult,
  ChildSummaryInput,
  ChildSummaryResult,
  StudyPathInput,
  StudyPathResult,
  AiUsageStats,
  ExplainErrorInput,
  ExplainErrorResult,
} from "./types"

// ---------------------------------------------------------------------------
// 辅助：并行校验多个权限
// ---------------------------------------------------------------------------

const requireAiPermission = async (
  ...permissions: readonly Permission[]
): Promise<{ userId: string }> => {
  const results = await Promise.all(
    permissions.map((p) => requirePermission(p))
  )
  return { userId: results[0].userId }
}

// ---------------------------------------------------------------------------
// AI 聊天
// ---------------------------------------------------------------------------

export async function aiChatAction(input: {
  messages: AiChatMessage[]
  providerId?: string
}): Promise<ActionState<AiChatResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requirePermission(Permissions.AI_CHAT)
    const parsed = AiChatInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() =>
      service.chat(parsed.data.messages, {
        providerId: parsed.data.providerId,
      })
    )
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.chatFailed") }
  }
}

// ---------------------------------------------------------------------------
// 相似题推荐
// ---------------------------------------------------------------------------

export async function suggestSimilarQuestionsAction(
  input: SimilarQuestionInput
): Promise<ActionState<SimilarQuestionResult[]>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requireAiPermission(
      Permissions.AI_CHAT,
      Permissions.ERROR_BOOK_READ
    )
    const parsed = SimilarQuestionInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() =>
      service.suggestSimilarQuestions(parsed.data)
    )
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.suggestionFailed") }
  }
}

// ---------------------------------------------------------------------------
// AI 辅助批改
// ---------------------------------------------------------------------------

export async function suggestGradingAction(
  input: GradingInput
): Promise<ActionState<GradingSuggestion>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requireAiPermission(
      Permissions.AI_CHAT,
      Permissions.HOMEWORK_GRADE
    )
    const parsed = GradingInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() => service.suggestGrading(parsed.data))
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.gradingFailed") }
  }
}

// ---------------------------------------------------------------------------
// 备课内容生成
// ---------------------------------------------------------------------------

export async function generateLessonContentAction(
  input: LessonContentInput
): Promise<ActionState<LessonContentResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requireAiPermission(
      Permissions.AI_CHAT,
      Permissions.LESSON_PLAN_READ
    )
    const parsed = LessonContentInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() =>
      service.generateLessonContent(parsed.data)
    )
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.contentFailed") }
  }
}

// ---------------------------------------------------------------------------
// 题目变体生成
// ---------------------------------------------------------------------------

export async function generateQuestionVariantAction(
  input: QuestionVariantInput
): Promise<ActionState<QuestionVariantResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requireAiPermission(
      Permissions.AI_CHAT,
      Permissions.EXAM_AI_GENERATE
    )
    const parsed = QuestionVariantInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() =>
      service.generateQuestionVariant(parsed.data)
    )
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.variantFailed") }
  }
}

// ---------------------------------------------------------------------------
// 薄弱点分析
// ---------------------------------------------------------------------------

export async function analyzeWeaknessAction(
  input: WeaknessAnalysisInput
): Promise<ActionState<WeaknessAnalysisResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requireAiPermission(
      Permissions.AI_CHAT,
      Permissions.ERROR_BOOK_READ
    )
    const parsed = WeaknessAnalysisInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() => service.analyzeWeakness(parsed.data))
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.analysisFailed") }
  }
}

// ---------------------------------------------------------------------------
// 家长 AI 学情摘要
// ---------------------------------------------------------------------------

export async function generateChildSummaryAction(
  input: ChildSummaryInput
): Promise<ActionState<ChildSummaryResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requirePermission(Permissions.AI_CHAT)
    const parsed = ChildSummaryInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() => service.generateChildSummary(parsed.data))
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("parent.error") }
  }
}

// ---------------------------------------------------------------------------
// 学生学习路径推荐
// ---------------------------------------------------------------------------

export async function recommendStudyPathAction(
  input: StudyPathInput
): Promise<ActionState<StudyPathResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requirePermission(Permissions.AI_CHAT)
    const parsed = StudyPathInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const serviceInput: StudyPathInput = { ...parsed.data }

    // V3：知识图谱集成（对标 Squirrel AI 纳米级知识图谱）
    // 若传入 textbookId 但未传入 knowledgeGraph，自动从 textbooks 模块获取
    if (parsed.data.textbookId && !parsed.data.knowledgeGraph) {
      try {
        const [kps, masteryMap] = await Promise.all([
          getKnowledgePointsWithRelations(parsed.data.textbookId),
          getStudentKpMastery(parsed.data.studentId, parsed.data.textbookId),
        ])

        if (kps.length > 0) {
          serviceInput.knowledgeGraph = {
            nodes: kps.map((kp) => ({
              id: kp.id,
              name: kp.name,
              level: kp.level,
              masteryLevel: masteryMap.get(kp.id)?.masteryLevel,
            })),
            edges: kps
              .flatMap((kp) =>
                (kp.prerequisiteIds ?? []).map((prereqId) => ({
                  from: prereqId,
                  to: kp.id,
                  type: "prerequisite" as const,
                }))
              ),
          }

          // 同步填充 currentMastery（若未传入）
          if (!serviceInput.currentMastery || serviceInput.currentMastery.length === 0) {
            serviceInput.currentMastery = kps.flatMap((kp) => {
              const m = masteryMap.get(kp.id)
              if (!m) return []
              return [{
                knowledgePoint: kp.name,
                masteryLevel: Math.round((m.masteryLevel / 100) * 5),
                errorCount: m.totalQuestions - m.correctQuestions,
              }]
            })
          }
        }
      } catch {
        // 知识图谱获取失败不阻断主流程，降级为无图谱模式
      }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() => service.recommendStudyPath(serviceInput))
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("studyPath.error") }
  }
}

// ---------------------------------------------------------------------------
// 管理员 AI 使用统计
// ---------------------------------------------------------------------------

export async function getAiUsageStatsAction(): Promise<ActionState<AiUsageStats>> {
  const t = await getTranslations("ai")
  try {
    await requirePermission(Permissions.AI_CONFIGURE)

    // 从 data-access 层获取真实聚合统计
    // 当前为内存事件存储（单实例），生产环境应查询 DB 或 Redis
    const stats = await getAiUsageStats()

    return { success: true, data: stats }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.statsFailed") }
  }
}

// ---------------------------------------------------------------------------
// 错题 AI 解释（P2-1 新增）
// ---------------------------------------------------------------------------

export async function explainErrorAction(
  input: ExplainErrorInput
): Promise<ActionState<ExplainErrorResult>> {
  const t = await getTranslations("ai")
  try {
    const ctx = await requireAiPermission(
      Permissions.AI_CHAT,
      Permissions.ERROR_BOOK_READ
    )
    const parsed = ExplainErrorInputSchema.safeParse(input)
    if (!parsed.success) {
      return { success: false, message: t("error.invalidInput") }
    }

    const service = createAiService(ctx.userId)
    const result = await safeAiCall(() => service.explainError(parsed.data))
    if (!result.ok) {
      return { success: false, message: result.message }
    }
    return { success: true, data: result.data }
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return { success: false, message: error.message }
    }
    return { success: false, message: t("error.analysisFailed") }
  }
}
