export async function generateGemini(prompt: string, systemPrompt: string): Promise<string> {
  // Use the fixed API key provided by the user
  const apiKey = 'AIzaSyDizFnYYnsBRBCfTuT9xhIPBXY0jFQd7HA';


  // Model fallback list - using current stable and experimental versions
  const modelOptions = [
    'gemini-3.1-flash',
    'gemini-3.1-pro',
    'gemini-3.1-flash-lite',
    'gemini-2.5-flash',
    'gemini-2.5-pro'
  ];

  let lastError: any = null;

  for (const modelName of modelOptions) {
    try {
      console.log(`Trying Gemini model: ${modelName}...`);
      const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${apiKey}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          contents: [{
            parts: [{
              text: `${systemPrompt}\n\nTask: ${prompt}`
            }]
          }],
          generationConfig: {
            maxOutputTokens: 4096,
            temperature: 0.2
          }
        })
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        console.warn(`Model ${modelName} failed:`, errorData);
        lastError = errorData;
        continue; // Try next model
      }

      const data = await response.json();
      console.log(`Successfully used model: ${modelName}`);
      return data.candidates[0].content.parts[0].text;
    } catch (err) {
      console.error(`Fetch error with ${modelName}:`, err);
      lastError = err;
    }
  }

  let errorMessage = lastError?.error?.message || lastError?.message || 'All Gemini models failed.';
  
  // Check if it's a quota error (429)
  if (lastError?.error?.code === 429 || lastError?.status === 429 || errorMessage.toLowerCase().includes('quota') || errorMessage.toLowerCase().includes('429')) {
    errorMessage = 'Gemini API quota exceeded. You may need to wait or switch to a paid billing plan in Google AI Studio.';
  }

  throw new Error(errorMessage + ' Check console for details.');
}
