import requests
import os
from dotenv import load_dotenv

def test_gemini():
    # Load .env
    load_dotenv()
    
    # Try multiple key names
    key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
    
    print("--- QualiLearn AI Diagnostic ---")
    if not key:
        print("[FAIL] No API Key found in .env or environment variables.")
        print("Please add GEMINI_API_KEY=your_key_here to your .env file.")
        return

    print(f"[INFO] Using API Key starting with: {key[:8]}...")
    
    model = "gemini-1.5-flash"
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}"
    
    payload = {
        "contents": [{"parts": [{"text": "Hello, are you online?"}]}]
    }
    
    try:
        print(f"[INFO] Connecting to {model}...")
        r = requests.post(url, json=payload, timeout=15)
        
        if r.status_code == 200:
            print("[SUCCESS] Gemini API is responding correctly!")
            data = r.json()
            response_text = data['candidates'][0]['content']['parts'][0]['text']
            print(f"[RESPONSE] AI says: {response_text.strip()}")
        else:
            print(f"[FAIL] API returned error code {r.status_code}")
            print(f"[DEBUG] Error message: {r.text}")
            
    except Exception as e:
        print(f"[FAIL] Connection Error: {str(e)}")

if __name__ == "__main__":
    test_gemini()
