import type { MixedGenerationInput } from "./dashboard-teacher-assignments.data";
import type { AssignmentSetupForm, QuestionGenerationForm } from "./dashboard-teacher-assignment-create.types";
import { GENERATION_TOPIC_OPTIONS } from "./dashboard-teacher-assignment-create.constants";

export const parseOptionalInteger = (value: string) => {
	const trimmed = value.trim();
	if (!trimmed) return undefined;
	const parsed = Number(trimmed);
	return Number.isInteger(parsed) ? parsed : Number.NaN;
};

export const buildMixedGenerationInput = (form: AssignmentSetupForm): MixedGenerationInput | null => {
	if (!form.useMixedGeneration) return null;

	const parsedTotalQuestions = Number(form.totalQuestions);
	const parsedPersonalizedRatio = Number(form.personalizedRatio);
	const parsedSeed = parseOptionalInteger(form.seed);

	return {
		primaryTopic: form.primaryTopic,
		primaryDifficulty: form.primaryDifficulty,
		totalQuestions: parsedTotalQuestions,
		personalizedRatio: Number.isFinite(parsedPersonalizedRatio) ? parsedPersonalizedRatio / 100 : undefined,
		seed: parsedSeed,
		personalizedDifficulty: form.personalizedDifficulty,
		subject: form.subject,
		questionStatus: "published",
		questionSource: "assignment_student_generated",
	};
};

export const mergeSelectedQuestionIds = (currentIds: number[], generatedIds: number[]) => Array.from(new Set([...currentIds, ...generatedIds]));

export const buildGenerationSuccessMessage = (generationForm: QuestionGenerationForm, count: number, seed: number) => {
	const topicLabel = GENERATION_TOPIC_OPTIONS.find((option) => option.value === generationForm.topic)?.label ?? "Generated";
	return `Generated ${count} ${generationForm.difficulty} ${topicLabel} question${count === 1 ? "" : "s"} and auto-selected ${count === 1 ? "it" : "them"} for this assignment. Seed: ${seed}.`;
};
