import { GoogleGenAI, Type } from "@google/genai";

export const generateSampleQuestion = async (topic: string): Promise<any | null> => {
    if (!process.env.GEMINI_API_KEY) {
        console.warn("API Key is missing. Returning mock data for demonstration.");
        return {
            question: `This is a simulated AI question about ${topic}. (Add API_KEY to env for real AI generation). What is the powerhouse of the cell?`,
            options: ["Nucleus", "Mitochondria", "Ribosome", "Endoplasmic Reticulum"],
            correctAnswerIndex: 1,
            explanation: "Mitochondria are often referred to as the powerhouse of the cell because they generate most of the cell's supply of adenosine triphosphate (ATP), used as a source of chemical energy."
        };
    }

    try {
        const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

        const response = await ai.models.generateContent({
            model: "gemini-2.5-flash",
            contents: `Generate a difficult multiple-choice question about "${topic}" suitable for a competitive exam student.`,
            config: {
                responseMimeType: "application/json",
                responseSchema: {
                    type: Type.OBJECT,
                    properties: {
                        question: { type: Type.STRING },
                        options: {
                            type: Type.ARRAY,
                            items: { type: Type.STRING },
                            minItems: 4,
                            maxItems: 4
                        },
                        correctAnswerIndex: { type: Type.INTEGER, description: "Index of the correct option (0-3)" },
                        explanation: { type: Type.STRING, description: "Brief explanation of the correct answer" }
                    },
                    required: ["question", "options", "correctAnswerIndex", "explanation"]
                }
            }
        });

        if (response.text) {
            return JSON.parse(response.text);
        }
        return null;
    } catch (error) {
        console.error("Failed to generate question:", error);
        return null;
    }
};