User: 20+21+21+20+24+23+21+27+27+27+6+25+23+16+20+29+29+30+30+30+30+30+26+21+23+20+23
Assistant: The sum of the numbers you provided is 640.
User: this is not fetching groovy questions find out why , help to debug
starttest: async ({ fetch, request, locals: { supabase, getSession } }) => {
  try {
    // Get form data
    const formData = await request.formData();
    const assessment_id = formData.get('assessmentId');
    if (!assessment_id) throw new Error('Assessment ID not found');

    // Fetch assessment skills
    const { data: assessmentData, error: assessmentError } = await supabase
      .from('assessments')
      .select('*')
      .eq('id', assessment_id)
      .single();
    if (assessmentError) throw new Error(`Error fetching assessment details: ${assessmentError.message}`);

    // Parse skills list
    const skillsList = Array.isArray(assessmentData.skills_list)
      ? assessmentData.skills_list
      : assessmentData.skills_list.split(',').map(skill => skill.trim());

    // Extract duration
    const { duration } = assessmentData;

    // Calculate total number of coding questions based on duration
    const totalCodingQuestions = Math.floor(duration / 5); // For example, 1 question for every 5 minutes
    console.log('Total Coding Questions Based on Duration:', totalCodingQuestions);

    // Separate coding and non-coding skills
    const codingSkills = skillsList.filter(skill => skill.includes('Coding'));
    const nonCodingSkills = skillsList.filter(skill => !skill.includes('Coding'));

    console.log('Coding Skills:', codingSkills);
    console.log('Non-Coding Skills:', nonCodingSkills);

    let codingQuestions = [];

    // Fetch coding questions if necessary
    if (codingSkills.length > 0 && totalCodingQuestions > 0) {
      const formattedSkills = codingSkills.map(skill => skill.split(':')[0].trim().split(' ')[0]);
      console.log('Formatted Skills:', formattedSkills);
      const { data: fetchedCodingQuestions, error: codingError } = await supabase
        .from('questions')
        .select('*')
        .eq('question_type', 'Coding')
        .in('skill', formattedSkills);

      if (codingError) throw new Error(`Error fetching coding questions: ${codingError.message}`);

      console.log('Fetched Coding Questions:', fetchedCodingQuestions.length);

      // Use a Set to avoid duplicates
      const uniqueQuestions = new Set();
      const skillQuestionMap = {};

      // Distribute questions by skill
      fetchedCodingQuestions.forEach(question => {
        const skill = question.skill.split(' ')[0]; // Get the skill name
        if (!skillQuestionMap[skill]) {
          skillQuestionMap[skill] = [];
        }
        skillQuestionMap[skill].push(question);
      });

      // Calculate how many questions to take from each skill
      const questionsPerSkill = Math.floor(totalCodingQuestions / Object.keys(skillQuestionMap).length);
      console.log('Questions per Skill:', questionsPerSkill);

      // Select questions from each skill
      for (const skill in skillQuestionMap) {
        const questions = shuffle(skillQuestionMap[skill]);
        const selectedQuestions = questions.slice(0, questionsPerSkill);
        selectedQuestions.forEach(q => uniqueQuestions.add(q)); // Add to Set to avoid duplicates
        console.log('Selected Questions from Skill:', skill, selectedQuestions.length);
        console.log('Unique Questions:', uniqueQuestions.size);
      }

      // Convert Set back to Array
      codingQuestions = Array.from(uniqueQuestions);
      console.log('Initial Unique Coding Questions:', codingQuestions.length);

      // If we have fewer questions than needed, select additional questions
      while (codingQuestions.length < totalCodingQuestions) {
        const remainingQuestions = fetchedCodingQuestions.filter(q => !codingQuestions.includes(q));
        if (remainingQuestions.length === 0) break; // No more questions to select
        const additionalQuestion = shuffle(remainingQuestions)[0]; // Randomly select one
        codingQuestions.push(additionalQuestion);
      }

      // Limit to the total coding questions based on duration
      codingQuestions = codingQuestions.slice(0, totalCodingQuestions);
      console.log('Final Coding Questions:', codingQuestions.length);
    }

    // Fetch MCQ questions if there are no coding questions or if you want to include them
    let mcqQuestions = [];
    if (nonCodingSkills.length > 0 || codingQuestions.length === 0) {
      const response = await fetch('../api/questions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ assessment_id })
      });
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      mcqQuestions = await response.json();
    }

    // Filter out coding questions from MCQs
    const filteredMcqQuestions = mcqQuestions.filter(question => question.question_type !== 'Coding');

    // Combine MCQ and coding questions
    const combinedQuestions = [...filteredMcqQuestions, ...codingQuestions];

    console.log('Combined Questions Length:', combinedQuestions.length);

    return { questions: combinedQuestions };
  } catch (error) {
    console.error('An error occurred:', error);
    return { error: error.message };
  }

  // Helper function to shuffle an array (Fisher-Yates shuffle)
  function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]]; // Swap elements
    }
    return array; // Return the shuffled array
  }
},

below are some consolelogs for refrence
questions from svelte part front me undefined
 {
  id: 138,
  created_at: '2024-10-08T02:18:30.026+00:00',
  assessment_name: 'mix test 2 for new',
  assessment_details: '',
  skills_list: 'c Coding: 0,c++ Coding: 0,groovy Coding: 0,Haskell Coding: 0,tcl Coding: 0,lua Coding: 0',
  duration: 40,
  auto_gen: true,
  user_id: 'f6f44369-a4f3-48e4-bcdd-c4de7dc46e70'
} assessmentDetails
Total Coding Questions Based on Duration: 8
Coding Skills: [
  'c Coding: 0',
  'c++ Coding: 0',
  'groovy Coding: 0',
  'Haskell Coding: 0',
  'tcl Coding: 0',
  'lua Coding: 0'
]
Non-Coding Skills: []
Formatted Skills: [ 'c', 'c++', 'groovy', 'Haskell', 'tcl', 'lua' ]
Fetched Coding Questions: 105
Questions per Skill: 1
Selected Questions from Skill: c 1
Unique Questions: 1
Selected Questions from Skill: lua 1
Unique Questions: 2
Selected Questions from Skill: c++ 1
Unique Questions: 3
Selected Questions from Skill: tcl 1
Unique Questions: 4
Selected Questions from Skill: Haskell 1
Unique Questions: 5
Initial Unique Coding Questions: 5
Final Coding Questions: 8
Combined Questions Length: 8
questions from svelte part front me undefined
 {
  id: 138,
  created_at: '2024-10-08T02:18:30.026+00:00',
  assessment_name: 'mix test 2 for new',
  assessment_details: '',
  skills_list: 'c Coding: 0,c++ Coding: 0,groovy Coding: 0,Haskell Coding: 0,tcl Coding: 0,lua Coding: 0',
  duration: 40,
  auto_gen: true,
  user_id: 'f6f44369-a4f3-48e4-bcdd-c4de7dc46e70'
} assessmentDetails

Assistant: