import * as z from "zod"
import type { Question } from "@/modules/questions/types"
import type { AiProviderSummary } from "@/modules/settings/actions"
import type { ExamNode } from "./assembly/selected-question-list"

export const formSchema = z.object({
  title: z.string().optional(),
  subject: z.string().optional(),
  grade: z.string().optional(),
  difficulty: z.string().optional(),
  totalScore: z.coerce.number().min(1, "Total score must be at least 1.").optional(),
  durationMin: z.coerce.number().min(10, "Duration must be at least 10 minutes.").optional(),
  scheduledAt: z.string().optional(),
  mode: z.enum(["manual", "ai", "rich"]),
  aiSourceText: z.string().optional(),
  aiQuestionCount: z.coerce.number().min(1).max(200).optional(),
  aiProviderId: z.string().optional(),
  // Exam mode + proctoring config
  examMode: z.enum(["homework", "timed", "proctored"]).default("homework"),
  durationMinutes: z.coerce.number().int().min(1).nullable().optional(),
  shuffleQuestions: z.boolean().default(false),
  allowLateStart: z.boolean().default(false),
  lateStartGraceMinutes: z.coerce.number().int().min(0).default(0),
  antiCheatEnabled: z.boolean().default(false),
}).superRefine((data, ctx) => {
  // 富文本模式不需要表单校验,直接跳转到 /teacher/exams/new
  if (data.mode === "rich") return

  // 监考模式必须设置考试时长
  if (data.examMode === "proctored" && (data.durationMinutes === null || data.durationMinutes === undefined || data.durationMinutes < 1)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["durationMinutes"],
      message: "Duration is required in proctored mode.",
    })
  }
  // 限时/监考模式必须设置考试时长
  if (data.examMode === "timed" && (data.durationMinutes === null || data.durationMinutes === undefined || data.durationMinutes < 1)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["durationMinutes"],
      message: "Duration is required in timed mode.",
    })
  }
  if (data.mode === "ai") {
    if (!data.aiSourceText?.trim()) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["aiSourceText"],
        message: "Source exam text is required for AI generation.",
      })
    }
    return
  }
  if (!data.title?.trim()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["title"],
      message: "Title must be at least 2 characters.",
    })
  }
  if (!data.subject?.trim()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["subject"],
      message: "Subject is required.",
    })
  }
  if (!data.grade?.trim()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["grade"],
      message: "Grade is required.",
    })
  }
  if (!data.difficulty?.trim()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["difficulty"],
      message: "Difficulty is required.",
    })
  }
  if (typeof data.totalScore !== "number") {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["totalScore"],
      message: "Total score must be at least 1.",
    })
  }
  if (typeof data.durationMin !== "number") {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["durationMin"],
      message: "Duration must be at least 10 minutes.",
    })
  }
})

export type ExamFormValues = z.infer<typeof formSchema>

export type PreviewQuestion = {
  id: string
  type: Question["type"]
  difficulty: number
  score: number
  content: Question["content"]
}

export type EditableQuestionContent = {
  text: string
  options: Array<{ id: string; text: string; isCorrect: boolean }>
  subQuestions: Array<{ id: string; text: string; answer?: string; score?: number }>
}

export type PreviewSnapshotMeta = {
  subject: string
  grade: string
  durationMin: number
  totalScore: number
}

export type PreviewBackgroundTask = {
  id: string
  createdAt: number
  status: "queued" | "running" | "success" | "failed"
  title: string
  signature: string
  message?: string
  result?: {
    title: string
    nodes: ExamNode[]
    rawOutput: string
    meta: PreviewSnapshotMeta
    formValues: Pick<ExamFormValues, "title" | "subject" | "grade" | "difficulty" | "totalScore" | "durationMin" | "aiSourceText" | "aiQuestionCount" | "aiProviderId">
  }
}

export const aiProviderLabels: Record<AiProviderSummary["provider"], string> = {
  zhipu: "智谱",
  openai: "OpenAI",
  gemini: "Gemini",
  custom: "Custom",
  ollama: "Ollama",
}

export const defaultValues: Partial<ExamFormValues> = {
  title: "",
  subject: "",
  grade: "",
  difficulty: "3",
  totalScore: 100,
  durationMin: 90,
  mode: "manual",
  scheduledAt: "",
  aiSourceText: "",
  aiQuestionCount: undefined,
  aiProviderId: "",
  examMode: "homework",
  durationMinutes: null,
  shuffleQuestions: false,
  allowLateStart: false,
  lateStartGraceMinutes: 0,
  antiCheatEnabled: false,
}

export const previewTaskStorageKey = "exam-preview-background-tasks:v1"
