"""
Gemini API Quota Diagnostic Script
Checks if your GOOGLE_API_KEY has valid quota and can make requests.
"""

import os
import sys
from pathlib import Path
from dotenv import load_dotenv

# Load .env from project root
load_dotenv(Path(__file__).parent.parent / ".env")

API_KEY = os.getenv("GOOGLE_API_KEY")

if not API_KEY:
    print("❌ GOOGLE_API_KEY not set in environment or .env file")
    sys.exit(1)

print(f"🔑 API Key: {API_KEY[:10]}...{API_KEY[-4:]} ({len(API_KEY)} chars)")

# --- Step 1: Check if the SDK is installed ---
try:
    from google import genai
    print("✅ google-genai SDK installed")
except ImportError:
    print("❌ google-genai SDK not installed. Run: pip install google-genai")
    sys.exit(1)

# --- Step 2: Create client ---
client = genai.Client(api_key=API_KEY)

# --- Step 3: List available models (doesn't consume quota) ---
print("\n📋 Checking available models...")
try:
    models = list(client.models.list())
    flash_models = [m.name for m in models if "flash" in m.name.lower()]
    print(f"✅ API key is valid — {len(models)} models available")
    print(f"   Flash models: {flash_models[:5]}")
except Exception as e:
    print(f"❌ API key invalid or network error: {e}")
    sys.exit(1)

# --- Step 4: Try a minimal generation (tests quota) ---
print("\n🧪 Testing generation (minimal request)...")
test_model = "gemini-2.0-flash"
try:
    response = client.models.generate_content(
        model=test_model,
        contents="Reply with exactly: OK",
        config={"temperature": 0, "max_output_tokens": 10},
    )
    text = response.text.strip() if response.text else "(empty)"
    print(f"✅ Generation succeeded with {test_model}!")
    print(f"   Response: {text}")
    print(f"\n🎉 Your API key has active quota. Gemini is working.")
except Exception as e:
    error_str = str(e)
    if "429" in error_str or "RESOURCE_EXHAUSTED" in error_str:
        print(f"❌ QUOTA EXHAUSTED for {test_model}")
        print(f"   Error: {error_str[:200]}")
        
        # Check if it's free tier
        if "free_tier" in error_str.lower():
            print(f"\n⚠️  This key is on the FREE TIER (not paid billing).")
            print(f"   The person who gave you this key needs to:")
            print(f"   1. Go to https://console.cloud.google.com/billing")
            print(f"   2. Link a billing account to the project")
            print(f"   3. Enable the Generative Language API with paid quota")
            print(f"   4. Check at https://ai.dev/rate-limit")
        else:
            print(f"\n⚠️  Paid quota may also be exhausted. Check usage at:")
            print(f"   https://ai.dev/rate-limit")
    elif "403" in error_str or "PERMISSION_DENIED" in error_str:
        print(f"❌ API key doesn't have permission for {test_model}")
        print(f"   Error: {error_str[:200]}")
    elif "404" in error_str or "NOT_FOUND" in error_str:
        print(f"❌ Model {test_model} not found. Trying gemini-1.5-flash...")
        try:
            response = client.models.generate_content(
                model="gemini-1.5-flash",
                contents="Reply with exactly: OK",
                config={"temperature": 0, "max_output_tokens": 10},
            )
            print(f"✅ gemini-1.5-flash works! Update your extractor model name.")
        except Exception as e2:
            print(f"❌ Also failed: {e2}")
    else:
        print(f"❌ Unexpected error: {error_str[:300]}")
