/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
*/
import {GoogleGenAI, GenerateContentResponse} from '@google/genai';
import {useEffect, useState} from 'react';
import ReactDOM from 'react-dom/client';

let apiKey: string | undefined = undefined;
let ai: GoogleGenAI | undefined;
let apiKeyError = '';

// Robustly check for process, process.env, and API_KEY availability
try {
  if (typeof process !== 'undefined' && process.env && typeof process.env.API_KEY === 'string' && process.env.API_KEY.trim() !== '') {
    apiKey = process.env.API_KEY;
  } else {
    if (typeof process === 'undefined' || !process.env) {
      apiKeyError = 'API Key not configured (process.env not accessible). Gemini features will be unavailable.';
    } else if (typeof process.env.API_KEY !== 'string') {
      apiKeyError = 'API Key not configured (API_KEY is not a string). Gemini features will be unavailable.';
    } else if (process.env.API_KEY.trim() === '') {
      apiKeyError = 'API Key is configured but empty. Gemini features will be unavailable.';
    } else { 
      apiKeyError = 'API Key not configured for an unknown reason. Gemini features will be unavailable.';
    }
    console.warn(apiKeyError + " Ensure process.env.API_KEY is set correctly in the execution environment.");
  }
} catch (e) {
  // This catch is a fallback, primary checks are above.
  apiKeyError = 'Error accessing API Key. Gemini features will be unavailable.';
  console.error(apiKeyError, e);
}

if (apiKey) {
  try {
    ai = new GoogleGenAI({apiKey: apiKey});
  } catch (e) {
    console.error("Error initializing GoogleGenAI with API Key:", e);
    apiKeyError = "Failed to initialize Gemini AI: " + (e instanceof Error ? e.message : String(e));
    ai = undefined; // Ensure ai is undefined on failure
  }
} else if (!apiKeyError) {
  // This case handles if apiKey is still undefined but no specific error was set above.
  apiKeyError = 'API Key not available for Gemini initialization. Gemini features will be unavailable.';
  console.warn(apiKeyError);
}


// Extend the Window interface to include our custom function
declare global {
  interface Window {
    getGeminiWeatherData: (promptContent: string) => Promise<string>;
  }
}

window.getGeminiWeatherData = async (promptContent: string): Promise<string> => {
  if (!ai || apiKeyError) { // Check if ai is not initialized or there was an apiKeyError
    return apiKeyError || "Gemini AI not initialized (API key issue or other initialization problem).";
  }

  try {
    // Use a valid and recommended model for non-streaming content generation
    const response: GenerateContentResponse = await ai.models.generateContent({
      model: 'gemini-2.5-flash-preview-04-17', 
      contents: promptContent,
    });
    return response.text;
  } catch (e) {
    console.error('Error fetching wind data from Gemini:', e);
    let displayError = 'Failed to fetch wind data.';
    if (e instanceof Error && e.message) {
        if (e.message.includes('API key not valid')) {
            displayError = 'Invalid API Key for Gemini.';
        } else if (e.message.toLowerCase().includes('quota')) {
            displayError = 'Gemini API quota exceeded.';
        } else if (e.message.toLowerCase().includes('candidate was blocked due to safety')) {
            displayError = 'Request blocked by safety settings.';
        } else {
            displayError = 'Error: ' + e.message;
        }
    }
    return displayError;
  }
};

function App() {
  const [error, setError] = useState('');

  useEffect(() => {
    if (apiKeyError) {
      setError(apiKeyError);
    } else if (!ai) { // If no API key error but AI still not initialized
        const errMsg = "Gemini AI client not initialized (Post API key check).";
        console.warn(errMsg); // Changed to warn as apiKeyError should catch most critical issues
        setError(errMsg);
    } else {
        setError(''); // Clear error if AI is initialized and no API key error
    }
  }, []); 

  if (error) {
    return (
      <div>
        <h1 style={{color: '#ffdddd', fontSize: '0.9em'}}>{error}</h1>
      </div>
    );
  }

  // If no error, render nothing or a minimal status if needed in the future.
  return null; 
}

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<App />);
} else {
  console.error("DOM element with ID 'root' not found. React app (index.tsx) will not be rendered.");
}