/**
 * Mock 课案数据（lesson-preparation 域，P7-insights 扩展）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 10 个我自己的课案（语文/数学/英语，覆盖小学/初中/高中）
 * - 20 个校内库课案（他人发布）
 * - 5 课案模板
 * - 课案日历 / 热力图
 * - CRUD：创建 / 更新 / Fork
 */

import type {
  LessonPlanItem,
  LessonPlanDetail,
  LessonPlanLibraryItem,
  LessonPlanCalendarMonth,
  LessonPlanCalendarDay,
  LessonPlanHeatmap,
  LessonPlanTemplate,
  CreateLessonPlanInput,
  UpdateLessonPlanInput,
  AIGenerateLessonPlanInput,
  AIGenerateLessonPlanResult,
} from "@/lib/graphql-p7-insights";

/** 学科 */
const SUBJECTS = ["语文", "数学", "英语"] as const;

/** 年级 */
const GRADES = ["小学三年级", "小学六年级", "初中一年级", "高中三年级"] as const;

/** 模板元信息 */
export const LESSON_PLAN_TEMPLATES: {
  id: LessonPlanTemplate;
  name: string;
  description: string;
}[] = [
  { id: "REGULAR", name: "常规教案", description: "标准课时教案：教学目标→重难点→教学过程→作业布置" },
  { id: "UNIT", name: "单元教案", description: "单元整体设计：单元目标→课时分配→阶段评估" },
  { id: "REVIEW", name: "复习教案", description: "复习课教案：知识梳理→典型例题→巩固练习" },
  { id: "ACTIVITY", name: "活动教案", description: "活动课教案：情境导入→合作探究→成果展示" },
  { id: "PERSONALIZED", name: "个性化教案", description: "分层教学：基础目标→进阶目标→差异化辅导" },
];

/** 课案内容模板（按学科生成 markdown） */
function planContent(
  title: string,
  subject: string,
  grade: string,
  chapter: string,
): string {
  return `# ${title}

## 基本信息
- 学科：${subject}
- 年级：${grade}
- 章节：${chapter}
- 课时：1 课时（40 分钟）

## 教学目标
1. 知识与技能：掌握 ${chapter} 的核心概念与基本运算
2. 过程与方法：通过情境导入与例题分析，培养逻辑推理能力
3. 情感态度价值观：激发学习兴趣，建立学科自信

## 教学重难点
- 重点：${chapter} 的定义与基本性质
- 难点：综合应用与变式训练

## 教学过程
### 一、情境导入（5 分钟）
通过生活实例引出 ${chapter} 的学习必要性。

### 二、新知讲解（15 分钟）
1. 概念引入：给出 ${chapter} 的规范定义
2. 性质剖析：列表对比关键性质
3. 典型例题：精选 3 道分层例题

### 三、巩固练习（12 分钟）
- 基础题：5 道
- 提升题：3 道
- 拓展题：1 道

### 四、课堂小结（5 分钟）
学生口述本节收获，教师补充完善。

### 五、作业布置（3 分钟）
- 必做：教材 P12 第 1-5 题
- 选做：探究题 1 道

## 板书设计
左侧：${chapter} 定义 | 中间：例题区 | 右侧：学生板演区

## 教学反思
课后填写：达成度 / 改进点 / 后续衔接`;
}

/** 10 个我的课案（基础定义） */
const MY_PLANS: Array<{
  id: string;
  title: string;
  subject: string;
  grade: string;
  chapter: string;
  status: "DRAFT" | "PUBLISHED" | "ARCHIVED";
  textbookId: string | null;
  textbookTitle: string | null;
  classIds: string[];
  updatedAt: string;
}> = [
  {
    id: "lp-001",
    title: "《岳阳楼记》第一课时",
    subject: "语文",
    grade: "初中一年级",
    chapter: "第二单元·岳阳楼记",
    status: "PUBLISHED",
    textbookId: "tb-001",
    textbookTitle: "小学语文三年级上册",
    classIds: ["550e8400-e29b-41d4-a716-446655440010"],
    updatedAt: "2026-07-01T09:00:00Z",
  },
  {
    id: "lp-002",
    title: "分数的初步认识",
    subject: "数学",
    grade: "小学三年级",
    chapter: "第七单元·分数的初步认识",
    status: "PUBLISHED",
    textbookId: "tb-002",
    textbookTitle: "小学数学六年级上册",
    classIds: ["550e8400-e29b-41d4-a716-446655440010"],
    updatedAt: "2026-07-02T14:30:00Z",
  },
  {
    id: "lp-003",
    title: "My Family 单元导入",
    subject: "英语",
    grade: "初中一年级",
    chapter: "Unit 1·My Family",
    status: "DRAFT",
    textbookId: "tb-003",
    textbookTitle: "初中英语七年级上册",
    classIds: ["550e8400-e29b-41d4-a716-446655440011"],
    updatedAt: "2026-07-03T10:15:00Z",
  },
  {
    id: "lp-004",
    title: "函数的单调性与极值",
    subject: "数学",
    grade: "高中三年级",
    chapter: "选修 2-2·导数应用",
    status: "PUBLISHED",
    textbookId: null,
    textbookTitle: null,
    classIds: ["550e8400-e29b-41d4-a716-446655440012"],
    updatedAt: "2026-07-05T08:45:00Z",
  },
  {
    id: "lp-005",
    title: "现代文阅读·论述类文本",
    subject: "语文",
    grade: "高中三年级",
    chapter: "第一轮复习·现代文阅读",
    status: "DRAFT",
    textbookId: null,
    textbookTitle: null,
    classIds: ["550e8400-e29b-41d4-a716-446655440012"],
    updatedAt: "2026-07-06T16:20:00Z",
  },
  {
    id: "lp-006",
    title: "Reading Strategies for Main Idea",
    subject: "英语",
    grade: "高中三年级",
    chapter: "高三复习·阅读理解",
    status: "PUBLISHED",
    textbookId: null,
    textbookTitle: null,
    classIds: ["550e8400-e29b-41d4-a716-446655440012"],
    updatedAt: "2026-07-07T11:00:00Z",
  },
  {
    id: "lp-007",
    title: "古诗词鉴赏·意象分析",
    subject: "语文",
    grade: "初中一年级",
    chapter: "第三单元·古诗词",
    status: "ARCHIVED",
    textbookId: "tb-001",
    textbookTitle: "小学语文三年级上册",
    classIds: ["550e8400-e29b-41d4-a716-446655440010"],
    updatedAt: "2026-06-28T09:30:00Z",
  },
  {
    id: "lp-008",
    title: "方程与不等式复习课",
    subject: "数学",
    grade: "小学六年级",
    chapter: "总复习·方程与不等式",
    status: "PUBLISHED",
    textbookId: "tb-002",
    textbookTitle: "小学数学六年级上册",
    classIds: ["550e8400-e29b-41d4-a716-446655440013"],
    updatedAt: "2026-07-08T13:45:00Z",
  },
  {
    id: "lp-009",
    title: "书面表达·议论文结构",
    subject: "英语",
    grade: "高中三年级",
    chapter: "高三复习·书面表达",
    status: "DRAFT",
    textbookId: null,
    textbookTitle: null,
    classIds: ["550e8400-e29b-41d4-a716-446655440012"],
    updatedAt: "2026-07-09T15:10:00Z",
  },
  {
    id: "lp-010",
    title: "实数与运算·总复习",
    subject: "数学",
    grade: "初中一年级",
    chapter: "第一章·实数",
    status: "PUBLISHED",
    textbookId: null,
    textbookTitle: null,
    classIds: ["550e8400-e29b-41d4-a716-446655440011"],
    updatedAt: "2026-07-10T10:00:00Z",
  },
];

/** 转 List item */
function toItem(p: typeof MY_PLANS[number]): LessonPlanItem {
  return { ...p };
}

/** 我的课案列表 */
export const mockLessonPlans: LessonPlanItem[] = MY_PLANS.map(toItem);

/** 按 ID 查询课案详情 */
export function findLessonPlanDetail(planId: string): LessonPlanDetail | null {
  const found = MY_PLANS.find((p) => p.id === planId);
  if (!found) return null;
  return {
    ...found,
    content: planContent(found.title, found.subject, found.grade, found.chapter),
    aiHistory: [
      {
        id: `ai-${found.id}-1`,
        prompt: `为「${found.title}」生成教学过程`,
        generatedAt: found.updatedAt,
        model: "edu-llm-p7-v1",
      },
    ],
    createdAt: "2026-06-20T08:00:00Z",
  };
}

/** 按学科筛选我的课案 */
export function filterLessonPlans(subject?: string | null): LessonPlanItem[] {
  if (!subject || subject === "全部") return mockLessonPlans;
  return mockLessonPlans.filter((p) => p.subject === subject);
}

/** 创建课案 */
export function createMockLessonPlan(
  input: CreateLessonPlanInput,
): LessonPlanItem {
  const now = new Date().toISOString();
  return {
    id: `lp-${String(Date.now()).slice(-6)}`,
    title: input.title,
    subject: input.subject,
    grade: input.grade,
    chapter: input.chapter,
    status: "DRAFT",
    textbookId: input.textbookId ?? null,
    textbookTitle: null,
    classIds: [],
    updatedAt: now,
  };
}

/** 更新课案（mock：返回更新后的最小信息） */
export function updateMockLessonPlan(
  input: UpdateLessonPlanInput,
): LessonPlanItem | null {
  const found = MY_PLANS.find((p) => p.id === input.planId);
  if (!found) return null;
  const now = new Date().toISOString();
  return {
    ...toItem(found),
    title: input.title ?? found.title,
    status: input.status ?? found.status,
    textbookId: input.textbookId !== undefined ? input.textbookId : found.textbookId,
    chapter: input.chapter ?? found.chapter,
    classIds: input.classIds ?? found.classIds,
    updatedAt: now,
  };
}

/** AI 生成课案（mock：返回一段 markdown） */
export function generateMockLessonPlan(
  input: AIGenerateLessonPlanInput,
): AIGenerateLessonPlanResult {
  const now = new Date().toISOString();
  const seq = String(Date.now()).slice(-6);
  const content = `# AI 生成教案：${input.chapter}

## 学科 ${input.subject} · 年级 ${input.grade}

## 教学目标
1. 掌握 ${input.chapter} 的核心概念
2. 能够运用相关知识解决典型问题
3. 培养学科思维与迁移能力

## 教学过程
### 一、导入（5 分钟）
${input.prompt}

### 二、新知讲解（15 分钟）
- 概念定义与示例
- 关键性质剖析
- 典型例题分层讲解

### 三、巩固练习（12 分钟）
- 基础题 / 提升题 / 拓展题

### 四、课堂小结（5 分钟）
### 五、作业布置（3 分钟）`;
  return {
    id: `ai-lp-${seq}`,
    content,
    summary: `围绕「${input.chapter}」生成的 ${input.subject} 教案，含教学目标、教学过程、作业布置。`,
    model: "edu-llm-p7-v1",
    generatedAt: now,
  };
}

/** 20 个校内库课案（他人发布） */
const AUTHORS = [
  "王老师", "李老师", "张老师", "陈老师", "刘老师",
  "赵老师", "黄老师", "周老师", "吴老师", "徐老师",
];

function buildLibraryItem(idx: number): LessonPlanLibraryItem {
  const subject = SUBJECTS[idx % SUBJECTS.length] ?? "数学";
  const grade = GRADES[idx % GRADES.length] ?? "初中一年级";
  const author = AUTHORS[idx % AUTHORS.length] ?? "佚名";
  const titles: Record<string, string[]> = {
    语文: ["《荷塘月色》赏析", "《背影》情感分析", "议论文写作入门", "古诗词意象专题"],
    数学: ["二次函数图像", "概率统计初步", "立体几何证明", "导数综合应用"],
    英语: ["Reading for Theme", "Writing a Narrative", "Grammar in Context", "Listening Strategies"],
  };
  const subjectTitles = titles[subject] ?? ["通用教案"];
  const title = subjectTitles[idx % subjectTitles.length] ?? `${subject} 教案 ${idx}`;
  return {
    id: `lp-lib-${String(idx).padStart(3, "0")}`,
    title,
    author,
    subject,
    grade,
    chapter: `第 ${idx + 1} 章`,
    rating: Math.round((3.5 + (idx % 1.5)) * 10) / 10,
    forkCount: Math.floor(((idx * 7) % 50) + 5),
    updatedAt: `2026-06-${String(28 - (idx % 27)).padStart(2, "0")}T09:00:00Z`,
  };
}

export const mockLessonPlanLibrary: LessonPlanLibraryItem[] = Array.from(
  { length: 20 },
  (_, i) => buildLibraryItem(i),
);

/** 按学科 + 年级筛选校内库 */
export function filterLessonPlanLibrary(
  subject?: string | null,
  grade?: string | null,
): LessonPlanLibraryItem[] {
  return mockLessonPlanLibrary.filter((p) => {
    if (subject && subject !== "全部" && p.subject !== subject) return false;
    if (grade && grade !== "全部" && p.grade !== grade) return false;
    return true;
  });
}

/** Fork 课案（mock：复制为新课案） */
export function forkMockLessonPlan(planId: string): LessonPlanItem | null {
  const lib = mockLessonPlanLibrary.find((p) => p.id === planId);
  if (!lib) return null;
  const now = new Date().toISOString();
  return {
    id: `lp-${String(Date.now()).slice(-6)}`,
    title: `${lib.title}（Fork）`,
    subject: lib.subject,
    grade: lib.grade,
    chapter: lib.chapter,
    status: "DRAFT",
    textbookId: null,
    textbookTitle: null,
    classIds: [],
    updatedAt: now,
  };
}

/** 课案日历视图（按月份） */
export function getLessonPlanCalendar(
  year: number,
  month: number,
): LessonPlanCalendarMonth {
  // 当月每天有 0-3 个课案（确定性 mock）
  const daysInMonth = new Date(year, month, 0).getDate();
  const days: LessonPlanCalendarDay[] = [];
  for (let d = 1; d <= daysInMonth; d++) {
    const seed = (year * 100 + month) * 31 + d;
    const planCount = seed % 4 === 0 ? 2 : seed % 3 === 0 ? 1 : 0;
    if (planCount === 0) {
      days.push({ date: `${year}-${String(month).padStart(2, "0")}-${String(d).padStart(2, "0")}`, planCount: 0, planTitles: [] });
    } else {
      const titles: string[] = [];
      for (let i = 0; i < planCount; i++) {
        titles.push(`课案 ${d}-${i + 1}`);
      }
      days.push({
        date: `${year}-${String(month).padStart(2, "0")}-${String(d).padStart(2, "0")}`,
        planCount,
        planTitles: titles,
      });
    }
  }
  return { year, month, days };
}

/** 课标覆盖热力图（教材知识点 × 课案覆盖矩阵） */
export function getLessonPlanHeatmap(): LessonPlanHeatmap {
  const rows = ["函数", "方程", "几何", "概率", "统计", "数列", "导数", "实数"];
  const cols = ["lp-001", "lp-002", "lp-004", "lp-008", "lp-010"];
  const cells = rows.map((r) =>
    cols.map((c) => ({
      textbookKp: r,
      planIds: (r.charCodeAt(0) + c.charCodeAt(3)) % 3 === 0 ? [c] : [],
      covered: (r.charCodeAt(0) + c.charCodeAt(3)) % 3 === 0,
    })),
  ).flat();
  return { rows, cols, cells };
}
