import os 
from google import genai 
from dotenv import load_dotenv 

script_dir =os .path .dirname (os .path .abspath (__file__ ))
load_dotenv (os .path .join (script_dir ,'.env'))

class GeminiClient :
    def __init__ (self ):
        self .api_key =os .getenv ("GOOGLE_API_KEY")

        if not self .api_key :
            raise ValueError ("No GOOGLE_API_KEY found in .env file!")

        self .client =genai .Client (api_key =self .api_key )
        self .model_name ="gemini-3-pro-preview"

    def ask (self ,prompt ,context =""):
        try :
            if context :
                full_message =f"Background Context:\n{context }\n\nUser Question: {prompt }"
            else :
                full_message =prompt 

            response =self .client .models .generate_content (
            model =self .model_name ,
            contents =full_message ,
            config ={
            'system_instruction': (
                "You are Ethix, an expert sustainability AI assistant. "
                "Your mission is to analyze sustainability reports and provide data-driven insights. "
                "You have access to a database of ESG reports (including Georgetown University). "
                "CRITICAL INSTRUCTIONS: "
                "1. PRIORITIZE CONTEXT: If the provided background context contains relevant data, YOU MUST USE IT and explicitly cite it. "
                "2. DETECT GREENWASHING: Be vigilant for vague buzzwords ('eco-friendly', 'green') lacking specific metrics. Flag them. "
                "3. ACCURACY: Do not hallucinate data. If the context is empty or irrelevant to the query, state 'I don't have specific data on this in my current reports' before offering general expert knowledge. "
                "4. FORMATTING: Use Markdown. Keep answers professional, concise, and structured."
            )
            }
            )
            return response .text 

        except Exception as e :
            return f"Error talking to Gemini: {str (e )}"

if __name__ =="__main__":
    try :
        brain =GeminiClient ()
        print ("--- Testing Class Connection ---")
        print (brain .ask ("Hello! Give me a 1-sentence coding tip."))
    except Exception as e :
        print (f"Failed to start Gemini: {e }")