import { PartExam, SpeakingExam } from "@/interfaces/exam";
import { countCurrentExercises } from "@/utils/moduleUtils";

const calculateExerciseIndex = (
  exam: PartExam,
  partIndex: number,
  exerciseIndex: number,
  questionIndex: number
) => {
  let total = 0;
  // Count all exercises in previous parts
  for (let i = 0; i < partIndex; i++) {
    total += countCurrentExercises(
      exam.parts[i].exercises,
      exam.parts[i].exercises.length - 1
    );
  }
  // Count previous exercises in current part
  if (partIndex < exam.parts.length && exerciseIndex > 0) {
    total += countCurrentExercises(
      exam.parts[partIndex].exercises.slice(0, exerciseIndex),
      exerciseIndex - 1
    );
  }

  // Only pass questionIndex if current exercise is multiple choice
  const currentExercise = exam.parts[partIndex].exercises[exerciseIndex];
  if (currentExercise.type === "multipleChoice") {
    total += countCurrentExercises(
      [currentExercise],
      0,
      questionIndex
    );
    return total;
  }

  // Add 1 for non-MC exercises
  total += 1;
  return total;
};

const calculateExerciseIndexSpeaking = (
  exam: SpeakingExam,
  exerciseIndex: number,
  questionIndex: number
) => {
  let total = 0;

  for (let i = 0; i < exerciseIndex; i++) {
    total += exam.exercises[i].type === "speaking" ? 1 : exam.exercises[i].prompts.length;
  }

  total += exam.exercises[exerciseIndex].type === "speaking" ? 1 : questionIndex + 1;
  
  return total;
};

export {
  calculateExerciseIndex,
  calculateExerciseIndexSpeaking
};
