const { GoogleGenerativeAI } = require('@google/generative-ai');

// Initialize Gemini AI
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || 'your-gemini-api-key-here');

const generateQuizQuestions = async (stage, category, difficulty, count, topic = null) => {
    try {
        // Check if Gemini API key is available
        if (!process.env.GEMINI_API_KEY || process.env.GEMINI_API_KEY === 'your-gemini-api-key-here') {
            console.log('Gemini API key not configured, using fallback questions');
            const fallbackQuestions = generateFallbackQuestions(stage, category, difficulty, count);
            return {
                success: true,
                data: {
                    questions: fallbackQuestions,
                    generatedBy: 'Fallback System (No API Key)',
                    parameters: { stage, category, difficulty, count, topic }
                },
                warning: 'Gemini API key not configured, using fallback questions'
            };
        }

        const model = genAI.getGenerativeModel({ model: "gemini-pro" });

        // Add randomization to prevent repeated questions
        const randomSeed = Math.random().toString(36).substring(7);
        const timestamp = Date.now();
        
        // Create a detailed prompt for quiz generation
        const prompt = `Generate ${count} multiple choice quiz questions for ${stage} students in the ${category} category with ${difficulty} difficulty level.
        
        ${topic ? `Focus on the topic: ${topic}` : ''}
        
        IMPORTANT: Generate UNIQUE and DIVERSE questions. Do NOT repeat common questions. Be creative and varied.
        Use different question formats, wordings, and topics within the category.
        Avoid textbook-style questions. Make them interesting and engaging.
        
        Requirements:
        1. Each question should have exactly 4 options (A, B, C, D)
        2. Only one correct answer per question
        3. Include detailed explanations for each answer
        4. Questions should be age-appropriate for ${stage} students
        5. Difficulty should be ${difficulty}
        6. Category: ${category}
        7. Make questions UNIQUE and DIFFERENT from common textbook questions
        8. Vary the question types (definition, application, analysis, etc.)
        9. Use different phrasings and approaches for each question
        
        Random seed: ${randomSeed} - ${timestamp}
        
        Format the response as a JSON array with this structure:
        [
            {
                "question": "Question text here",
                "options": ["Option A", "Option B", "Option C", "Option D"],
                "correctAnswer": 0,
                "explanation": "Detailed explanation of the correct answer",
                "category": "${category}",
                "difficulty": "${difficulty}",
                "stage": "${stage}",
                "tags": ["tag1", "tag2", "tag3"],
                "questionId": "unique_${randomSeed}_1"
            }
        ]
        
        Make sure the JSON is valid and properly formatted.`;

        const result = await model.generateContent(prompt);
        const response = await result.response;
        const text = response.text();

        // Clean up the response text to extract JSON
        let jsonText = text.trim();
        
        // Remove markdown code blocks if present
        if (jsonText.startsWith('```json')) {
            jsonText = jsonText.replace(/^```json\n/, '').replace(/\n```$/, '');
        } else if (jsonText.startsWith('```')) {
            jsonText = jsonText.replace(/^```\n/, '').replace(/\n```$/, '');
        }

        // Parse the JSON response
        const questions = JSON.parse(jsonText);

        // Validate and format the questions
        const formattedQuestions = questions.map((q, index) => ({
            question: q.question,
            options: q.options || [],
            correctAnswer: q.correctAnswer || 0,
            explanation: q.explanation || 'No explanation provided.',
            category: q.category || category,
            difficulty: q.difficulty || difficulty,
            stage: q.stage || stage,
            tags: q.tags || [category, difficulty],
            source: 'Gemini AI',
            isActive: true
        }));

        return {
            success: true,
            data: {
                questions: formattedQuestions,
                generatedBy: 'Gemini AI',
                parameters: {
                    stage,
                    category,
                    difficulty,
                    count,
                    topic
                }
            }
        };

    } catch (error) {
        console.error('Gemini AI Quiz Generation Error:', error);
        
        // Fallback: Generate simple questions if AI fails
        const fallbackQuestions = generateFallbackQuestions(stage, category, difficulty, count);
        
        return {
            success: true,
            data: {
                questions: fallbackQuestions,
                generatedBy: 'Fallback System',
                parameters: {
                    stage,
                    category,
                    difficulty,
                    count,
                    topic
                }
            },
            warning: 'AI generation failed, using fallback questions'
        };
    }
};

// Fallback question generator with randomization
const generateFallbackQuestions = (stage, category, difficulty, count) => {
    const allFallbackQuestions = [
        // General Knowledge Questions
        {
            question: "What is the capital of India?",
            options: ["Mumbai", "Delhi", "Kolkata", "Chennai"],
            correctAnswer: 1,
            explanation: "Delhi is the capital of India and houses important government buildings like the Parliament and Rashtrapati Bhavan.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "india", "capitals"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which planet is known as the Red Planet?",
            options: ["Venus", "Mars", "Jupiter", "Saturn"],
            correctAnswer: 1,
            explanation: "Mars is called the Red Planet because of the iron oxide (rust) on its surface, which gives it a reddish appearance.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["science", "astronomy", "planets"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the largest ocean on Earth?",
            options: ["Atlantic", "Pacific", "Indian", "Arctic"],
            correctAnswer: 1,
            explanation: "The Pacific Ocean is the largest ocean on Earth, covering about 46% of Earth's water surface.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "oceans", "earth"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Who wrote the book 'War and Peace'?",
            options: ["Fyodor Dostoevsky", "Leo Tolstoy", "Anton Chekhov", "Nikolai Gogol"],
            correctAnswer: 1,
            explanation: "Leo Tolstoy wrote the famous novel 'War and Peace'.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["literature", "russian literature", "classics"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the smallest country in the world?",
            options: ["Monaco", "Nauru", "Vatican City", "San Marino"],
            correctAnswer: 2,
            explanation: "Vatican City is the smallest country in the world by both area and population.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "countries", "size"],
            source: 'Fallback System',
            isActive: true
        },
        
        // Science Questions
        {
            question: "What is the chemical symbol for water?",
            options: ["H2O", "CO2", "NaCl", "O2"],
            correctAnswer: 0,
            explanation: "Water is composed of two hydrogen atoms and one oxygen atom, hence the chemical formula H2O.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["chemistry", "molecules", "water"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which force pulls objects towards the Earth?",
            options: ["Magnetism", "Gravity", "Friction", "Electricity"],
            correctAnswer: 1,
            explanation: "Gravity is the force that attracts objects with mass towards each other, including objects towards the Earth.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["physics", "gravity", "forces"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the formula for calculating the area of a circle?",
            options: ["πr²", "2πr", "πd", "πr²/2"],
            correctAnswer: 0,
            explanation: "The area of a circle is calculated using the formula A = πr², where r is the radius.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["geometry", "formula", "circle"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which programming language was created by Guido van Rossum?",
            options: ["Java", "Python", "C++", "JavaScript"],
            correctAnswer: 1,
            explanation: "Python was created by Guido van Rossum and first released in 1991.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["programming", "python", "computer science"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the speed of light in vacuum?",
            options: ["300,000 km/s", "150,000 km/s", "450,000 km/s", "600,000 km/s"],
            correctAnswer: 0,
            explanation: "The speed of light in vacuum is approximately 300,000 kilometers per second.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["physics", "light", "speed"],
            source: 'Fallback System',
            isActive: true
        },
        
        // History Questions
        {
            question: "In which year did India gain independence?",
            options: ["1945", "1947", "1949", "1951"],
            correctAnswer: 1,
            explanation: "India gained independence from British rule on August 15, 1947.",
            category: 'history',
            difficulty: difficulty,
            stage: stage,
            tags: ["indian history", "independence", "1947"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Who was the first President of India?",
            options: ["Jawaharlal Nehru", "Rajendra Prasad", "Sardar Patel", "Dr. Ambedkar"],
            correctAnswer: 1,
            explanation: "Dr. Rajendra Prasad was the first President of India from 1950 to 1962.",
            category: 'history',
            difficulty: difficulty,
            stage: stage,
            tags: ["indian history", "presidents", "independence"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which dynasty built the Taj Mahal?",
            options: ["Mughal", "Mauryan", "Gupta", "Chola"],
            correctAnswer: 0,
            explanation: "The Taj Mahal was built by the Mughal Emperor Shah Jahan in memory of his wife Mumtaz Mahal.",
            category: 'history',
            difficulty: difficulty,
            stage: stage,
            tags: ["indian history", "mughal", "monuments"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "When did World War II end?",
            options: ["1943", "1944", "1945", "1946"],
            correctAnswer: 2,
            explanation: "World War II ended in 1945 with the surrender of Japan on September 2, 1945.",
            category: 'history',
            difficulty: difficulty,
            stage: stage,
            tags: ["world history", "world war", "1945"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Who discovered America?",
            options: ["Vasco da Gama", "Christopher Columbus", "Marco Polo", "Ferdinand Magellan"],
            correctAnswer: 1,
            explanation: "Christopher Columbus discovered America in 1492, although he was actually looking for a route to India.",
            category: 'history',
            difficulty: difficulty,
            stage: stage,
            tags: ["world history", "discovery", "america"],
            source: 'Fallback System',
            isActive: true
        },
        
        // Geography Questions
        {
            question: "What is the capital of Australia?",
            options: ["Sydney", "Melbourne", "Canberra", "Perth"],
            correctAnswer: 2,
            explanation: "Canberra is the capital city of Australia, not Sydney which is the largest city.",
            category: 'geography',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "capitals", "australia"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which is the longest river in the world?",
            options: ["Amazon", "Nile", "Mississippi", "Ganges"],
            correctAnswer: 1,
            explanation: "The Nile River is the longest river in the world, flowing through 11 countries in northeastern Africa.",
            category: 'geography',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "rivers", "nile"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the highest mountain in the world?",
            options: ["K2", "Mount Everest", "Kangchenjunga", "Lhotse"],
            correctAnswer: 1,
            explanation: "Mount Everest is the highest mountain in the world, standing at 8,848 meters above sea level.",
            category: 'geography',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "mountains", "everest"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which country has the most population?",
            options: ["India", "China", "United States", "Brazil"],
            correctAnswer: 1,
            explanation: "China has the largest population in the world, followed closely by India.",
            category: 'geography',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "population", "countries"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the largest continent?",
            options: ["Africa", "Europe", "Asia", "North America"],
            correctAnswer: 2,
            explanation: "Asia is the largest continent by both area and population, covering about 30% of Earth's land area.",
            category: 'geography',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "continents", "asia"],
            source: 'Fallback System',
            isActive: true
        },
        
        // Current Affairs Questions
        {
            question: "What does 'COVID-19' stand for?",
            options: ["Coronavirus Disease 2019", "Coronavirus Infection 2019", "Coronavirus Detection 2019", "Coronavirus Prevention 2019"],
            correctAnswer: 0,
            explanation: "COVID-19 stands for Coronavirus Disease 2019, referring to the disease caused by the SARS-CoV-2 virus.",
            category: 'current_affairs',
            difficulty: difficulty,
            stage: stage,
            tags: ["health", "pandemic", "covid"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which year was declared as the International Year of Millets?",
            options: ["2022", "2023", "2024", "2025"],
            correctAnswer: 1,
            explanation: "2023 was declared as the International Year of Millets by the United Nations.",
            category: 'current_affairs',
            difficulty: difficulty,
            stage: stage,
            tags: ["un", "millets", "2023"],
            source: 'Fallback System',
            isActive: true
        },
        
        // Class 11-12 Specific Questions
        {
            question: "What is the derivative of x²?",
            options: ["x", "2x", "x²", "2x²"],
            correctAnswer: 1,
            explanation: "The derivative of x² is 2x using the power rule of differentiation.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["mathematics", "calculus", "derivatives"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which law states that energy cannot be created or destroyed?",
            options: ["Newton's First Law", "Law of Conservation of Energy", "Ohm's Law", "Pascal's Law"],
            correctAnswer: 1,
            explanation: "The Law of Conservation of Energy states that energy cannot be created or destroyed, only converted from one form to another.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["physics", "energy", "conservation"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the IUPAC name of CH₃COOH?",
            options: ["Methanol", "Ethanol", "Acetic Acid", "Formic Acid"],
            correctAnswer: 2,
            explanation: "CH₃COOH is acetic acid according to IUPAC nomenclature.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["chemistry", "organic chemistry", "iupac"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which exam is conducted for admission to IITs?",
            options: ["JEE Main", "JEE Advanced", "NEET", "CLAT"],
            correctAnswer: 1,
            explanation: "JEE Advanced is conducted for admission to the Indian Institutes of Technology (IITs).",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["education", "engineering", "iit"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the full form of CBSE?",
            options: ["Central Board of Secondary Education", "Central Bureau of Secondary Education", "Central Board of School Education", "Central Bureau of School Education"],
            correctAnswer: 0,
            explanation: "CBSE stands for Central Board of Secondary Education.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["education", "cbse", "board"],
            source: 'Fallback System',
            isActive: true
        },
        
        // Graduation Specific Questions
        {
            question: "What is the study of the structure and function of cells called?",
            options: ["Anatomy", "Physiology", "Cytology", "Pathology"],
            correctAnswer: 2,
            explanation: "Cytology is the study of the structure and function of cells.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["biology", "cells", "cytology"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which programming paradigm is based on objects?",
            options: ["Procedural Programming", "Object-Oriented Programming", "Functional Programming", "Logic Programming"],
            correctAnswer: 1,
            explanation: "Object-Oriented Programming (OOP) is based on the concept of objects that contain data and code.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["programming", "oop", "computer science"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What does GDP stand for?",
            options: ["Gross Domestic Product", "General Development Program", "Government Development Policy", "Gross Domestic Policy"],
            correctAnswer: 0,
            explanation: "GDP stands for Gross Domestic Product, which measures the total value of goods and services produced in a country.",
            category: 'gk',
            difficulty: difficulty,
            stage: stage,
            tags: ["economics", "gdp", "economy"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "Which is the largest planet in our solar system?",
            options: ["Earth", "Saturn", "Jupiter", "Neptune"],
            correctAnswer: 2,
            explanation: "Jupiter is the largest planet in our solar system, more than twice as massive as all other planets combined.",
            category: 'science',
            difficulty: difficulty,
            stage: stage,
            tags: ["astronomy", "planets", "jupiter"],
            source: 'Fallback System',
            isActive: true
        },
        {
            question: "What is the capital of Australia?",
            options: ["Sydney", "Melbourne", "Canberra", "Perth"],
            correctAnswer: 2,
            explanation: "Canberra is the capital city of Australia, not Sydney which is the largest city.",
            category: 'geography',
            difficulty: difficulty,
            stage: stage,
            tags: ["geography", "capitals", "australia"],
            source: 'Fallback System',
            isActive: true
        }
    ];

    // Filter questions by category or use all questions if category not found
    const categoryQuestions = allFallbackQuestions.filter(q => 
        q.category === category || category === 'all' || !category
    );
    
    // If no questions found for the category, use all questions
    const questionsToUse = categoryQuestions.length > 0 ? categoryQuestions : allFallbackQuestions;
    
    // Return the requested number of questions with better randomization
    const result = [];
    const shuffledQuestions = [...questionsToUse].sort(() => Math.random() - 0.5);
    
    // If we need more questions than available, repeat but with modifications
    for (let i = 0; i < count; i++) {
        const originalQuestion = shuffledQuestions[i % shuffledQuestions.length];
        // Create a deep copy to avoid modifying the original
        const question = JSON.parse(JSON.stringify(originalQuestion));
        
        // Add unique randomization to prevent exact duplicates
        const randomId = Math.random().toString(36).substring(7);
        const timestamp = Date.now();
        question.questionId = `fallback_${randomId}_${i + 1}_${timestamp}`;
        question.category = category;
        question.stage = stage;
        question.difficulty = difficulty;
        
        // Add slight variations to repeated questions
        if (i >= shuffledQuestions.length) {
            question.tags = [...(question.tags || []), `variant_${i + 1}`];
            question.explanation = question.explanation + ` (Question ${i + 1})`;
        }
        
        result.push(question);
    }
    
    return result;
};

module.exports = {
    generateQuizQuestions
};
