/**
 * V5-21 A3/A4/A5：AI 差异化生成 + 课标实时核对 + 评估可解释。
 *
 * - A3：根据课案内容生成基础/提高/拓展三个层次的差异化教学建议
 * - A4：课标实时核对（检查课案是否覆盖教材课标要求）
 * - A5：评估可解释（对 exercise 节点给出评分依据说明）
 *
 * 复用 ai-feedback.ts 的 AI 调用模式，纯服务端模块。
 */
import "server-only";
import { env } from "@/env.mjs";
import { createAiChatCompletion } from "@/shared/lib/ai";
import { isRecord } from "@/shared/lib/type-guards";
import { z } from "zod";
import type { LessonPlanDocument, LessonPlanNode, DifferentiationLevel } from "../types";

/** A3：差异化教学建议 */
export interface DifferentiationSuggestion {
  level: DifferentiationLevel;
  /** 该层次的具体教学建议 */
  suggestions: string[];
  /** 适用学生描述 */
  targetStudents: string;
}

/** A4：课标核对结果 */
export interface CurriculumCheckItem {
  /** 课标要求（知识点名称） */
  requirement: string;
  /** 是否已覆盖 */
  covered: boolean;
  /** 覆盖方式说明（如已覆盖，说明在哪个节点覆盖） */
  explanation: string;
}

/** A5：可解释评估 */
export interface ExplainableAssessment {
  /** 节点 ID */
  nodeId: string;
  /** 评估结论 */
  conclusion: string;
  /** 评分依据（可解释性） */
  rationale: string;
  /** 改进建议 */
  suggestion: string;
}

// Zod schemas
const DifferentiationSuggestionSchema = z.object({
  level: z.enum(["basic", "intermediate", "advanced"]),
  suggestions: z.array(z.string()),
  targetStudents: z.string(),
});

const CurriculumCheckItemSchema = z.object({
  requirement: z.string(),
  covered: z.boolean(),
  explanation: z.string(),
});

const ExplainableAssessmentSchema = z.object({
  nodeId: z.string(),
  conclusion: z.string(),
  rationale: z.string(),
  suggestion: z.string(),
});

const DifferentiationResultSchema = z.object({
  items: z.array(DifferentiationSuggestionSchema),
});

const CurriculumCheckResultSchema = z.object({
  items: z.array(CurriculumCheckItemSchema),
});

const ExplainableAssessmentResultSchema = z.object({
  items: z.array(ExplainableAssessmentSchema),
});

const AI_DIFFERENTIATION_PROMPT = `你是教学设计专家。请基于以下课案内容，为三个层次的学生生成差异化教学建议：
- basic（基础生）：需要夯实基础
- intermediate（中等生）：需要巩固提升
- advanced（学优生）：需要拓展延伸

课案内容：
---
{doc}
---

返回 JSON 对象：{ items: [{ level, suggestions: [建议1, 建议2], targetStudents: "适用学生描述" }] }`;

const AI_CURRICULUM_CHECK_PROMPT = `你是教学设计专家。请核对以下课案是否覆盖教材课标要求。

课案内容：
---
{doc}
---

教材知识点列表：{kpList}

返回 JSON 对象：{ items: [{ requirement: "知识点名称", covered: true/false, explanation: "覆盖方式说明" }] }`;

const AI_EXPLAINABLE_PROMPT = `你是教学评价专家。请对以下课案中的练习节点给出可解释的评估。

课案内容：
---
{doc}
---

返回 JSON 对象：{ items: [{ nodeId: "节点ID", conclusion: "评估结论", rationale: "评分依据", suggestion: "改进建议" }] }`;

/** 安全提取节点文本 */
function extractNodeText(node: LessonPlanNode): string {
  const data = node.data as unknown;
  if (!isRecord(data)) return "";
  const html = typeof data.html === "string" ? data.html : "";
  const sourceText = typeof data.sourceText === "string" ? data.sourceText : "";
  return html || sourceText || "";
}

/** 构建课案摘要供 AI 分析 */
function buildDocSummary(doc: LessonPlanDocument): string {
  const teachingNodes = doc.nodes.filter(
    (n): n is LessonPlanNode => n.type !== "textbook_content",
  );
  return JSON.stringify(
    teachingNodes.slice(0, 20).map((n) => ({
      id: n.id,
      type: n.type,
      title: n.title,
      stage: n.stage,
      differentiation: n.differentiation,
      text: extractNodeText(n).slice(0, 200),
    })),
  );
}

/**
 * A3：AI 差异化教学建议生成。
 */
export async function generateDifferentiationSuggestions(
  doc: LessonPlanDocument,
): Promise<DifferentiationSuggestion[]> {
  const teachingNodes = doc.nodes.filter(
    (n): n is LessonPlanNode => n.type !== "textbook_content",
  );
  if (teachingNodes.length === 0) return [];

  const prompt = AI_DIFFERENTIATION_PROMPT.replace("{doc}", buildDocSummary(doc));

  try {
    const { content } = await createAiChatCompletion({
      messages: [{ role: "user", content: prompt }],
      model: env.AI_MODEL ?? "gpt-4o-mini",
      temperature: 0.5,
    });

    const jsonMatch = content.match(/\{[\s\S]*\}/);
    if (!jsonMatch) return [];

    const parsed: unknown = JSON.parse(jsonMatch[0]);
    const validated = DifferentiationResultSchema.safeParse(parsed);
    if (!validated.success) return [];

    return validated.data.items;
  } catch {
    return [];
  }
}

/**
 * A4：AI 课标实时核对。
 */
export async function checkCurriculumAlignment(
  doc: LessonPlanDocument,
  knowledgePoints: { id: string; name: string }[],
): Promise<CurriculumCheckItem[]> {
  if (knowledgePoints.length === 0) return [];

  const prompt = AI_CURRICULUM_CHECK_PROMPT
    .replace("{doc}", buildDocSummary(doc))
    .replace("{kpList}", JSON.stringify(knowledgePoints.slice(0, 50)));

  try {
    const { content } = await createAiChatCompletion({
      messages: [{ role: "user", content: prompt }],
      model: env.AI_MODEL ?? "gpt-4o-mini",
      temperature: 0.2,
    });

    const jsonMatch = content.match(/\{[\s\S]*\}/);
    if (!jsonMatch) return [];

    const parsed: unknown = JSON.parse(jsonMatch[0]);
    const validated = CurriculumCheckResultSchema.safeParse(parsed);
    if (!validated.success) return [];

    return validated.data.items;
  } catch {
    return [];
  }
}

/**
 * A5：AI 可解释评估。
 */
export async function generateExplainableAssessment(
  doc: LessonPlanDocument,
): Promise<ExplainableAssessment[]> {
  const exerciseNodes = doc.nodes.filter(
    (n): n is LessonPlanNode => n.type === "exercise",
  );
  if (exerciseNodes.length === 0) return [];

  const prompt = AI_EXPLAINABLE_PROMPT.replace("{doc}", buildDocSummary(doc));

  try {
    const { content } = await createAiChatCompletion({
      messages: [{ role: "user", content: prompt }],
      model: env.AI_MODEL ?? "gpt-4o-mini",
      temperature: 0.4,
    });

    const jsonMatch = content.match(/\{[\s\S]*\}/);
    if (!jsonMatch) return [];

    const parsed: unknown = JSON.parse(jsonMatch[0]);
    const validated = ExplainableAssessmentResultSchema.safeParse(parsed);
    if (!validated.success) return [];

    return validated.data.items;
  } catch {
    return [];
  }
}
