export async function generateGemini(prompt: string, systemPrompt: string): Promise<string> {
  // Try all possible ways to get the API key
  const apiKey = 
    (window as any).GEMINI_API_KEY ||
    localStorage.getItem('GEMINI_API_KEY') || 
    import.meta.env.VITE_GEMINI_API_KEY ||
    import.meta.env.GEMINI_API_KEY ||
    (process.env as any).GEMINI_API_KEY ||
    '';

  if (!apiKey) {
    console.error('No Gemini API Key found in env or storage');
    throw new Error('Gemini API Key not found. Please set VITE_GEMINI_API_KEY in .env or GEMINI_API_KEY in localStorage.');
  }

  // Model fallback list - updated for March 2026
  const modelOptions = [
    'gemini-2.5-flash',
    'gemini-2.5-flash-lite',
    'gemini-2.5-pro',
    'gemini-2.0-flash',
    'gemini-1.5-flash'
  ];

  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: 2048,
            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;
    }
  }

  throw new Error(lastError?.error?.message || lastError?.message || 'All Gemini models failed. Check console for details.');
}
