import { GoogleGenAI, Type } from "@google/genai"; import type { Case } from '../types'; const API_KEY = process.env.API_KEY; if (!API_KEY) { console.error("API_KEY environment variable not set. Gemini API calls will fail."); } const ai = new GoogleGenAI({ apiKey: API_KEY! }); const model = "gemini-2.5-flash"; const responseSchema = { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { "question": { "type": Type.STRING, "description": "Die klinische Fallfrage." }, "options": { "type": Type.ARRAY, // FIX: Added a missing comma after Type.STRING "items": { "type": Type.STRING }, "description": "Genau 4 Antwortoptionen." }, "answer": { "type": Type.INTEGER, "description": "Der Null-basierte Index der korrekten Antwort (0, 1, 2 oder 3)." }, "explanation": { "type": Type.STRING, "description": "Eine detaillierte medizinische Erklärung für die korrekte Antwort." } }, required: ["question", "options", "answer", "explanation"] } }; export async function fetchAIEnhancedCases(specialty: string, count: number): Promise { if (!API_KEY) { console.warn(`Skipping AI generation for ${specialty} due to missing API key.`); return []; } const userPrompt = `Generiere ${count} verschiedene, hochwertige Multiple-Choice-Fragen, die für eine medizinische Lizenzprüfung geeignet sind, speziell für das Fachgebiet **${specialty}** in deutscher Sprache. Jede Frage muss genau 4 Optionen haben.`; const systemPrompt = "Du bist ein erfahrener Oberarzt und medizinischer Ausbilder. Generiere nur das angeforderte JSON-Array mit genauen und klinisch relevanten Informationen in deutscher Sprache."; try { const response = await ai.models.generateContent({ model: model, // FIX: Simplified contents to be a string as per guidelines. contents: userPrompt, config: { // FIX: systemInstruction should be a string, not an object with a parts property. systemInstruction: systemPrompt, responseMimeType: "application/json", responseSchema: responseSchema, temperature: 0.8 } }); const jsonText = response.text; if (!jsonText) { throw new Error("API returned empty text response."); } const parsedJson = JSON.parse(jsonText); // Basic validation if (!Array.isArray(parsedJson) || parsedJson.length === 0) { throw new Error("API did not return a valid array of cases."); } return parsedJson as Case[]; } catch (error) { console.error(`Error generating AI cases for specialty "${specialty}":`, error); return []; // Return empty array on failure to allow fallback } }