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-2.0-flash"

    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 assistant. You have access to a database including Georgetown University sustainability reports. SEARCH THE PROVIDED CONTEXT CAREFULLY. If the context contains ANY information about Georgetown University or the user\'s query, matches, or partial matches, YOU MUST USE IT to answer. Ignore irrelevant parts of the context. If no context matches, provide general expert advice. Keep responses concise (max 6 sentences).'
            }
            )
            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 }")