#!/usr/bin/env python3
"""
Test direct Google API (bypassing proxy).
"""

import os
import sys
sys.path.append(os.getcwd())

# Temporarily remove GEMINI_BASE_URL to use direct API
os.environ.pop('GEMINI_BASE_URL', None)

from health.utils.env_loader import load_env_with_extras
from slack_bot.llm.gemini import GeminiLLM
from slack_bot.tools.registry import TOOLS_SCHEMA

load_env_with_extras()

print("=" * 60)
print("Testing Direct Google API (No Proxy)")
print("=" * 60)

# Check if we have GOOGLE_API_KEY or GEMINI_API_KEY
google_key = os.environ.get("GOOGLE_API_KEY") or os.environ.get("GEMINI_API_KEY")
if not google_key:
    print("\n❌ No Google API key found!")
    print("You need either GOOGLE_API_KEY or GEMINI_API_KEY in your .env")
    sys.exit(1)

# Temporarily set for direct API
if "GOOGLE_API_KEY" not in os.environ:
    os.environ["GOOGLE_API_KEY"] = google_key

# Remove base URL to force direct API
if "GEMINI_BASE_URL" in os.environ:
    del os.environ["GEMINI_BASE_URL"]

print(f"\nAPI Key: {google_key[:20]}...")
print(f"Using direct Google API")

try:
    llm = GeminiLLM()

    print(f"\nInitialized: use_proxy = {llm.use_proxy}")

    # Test with tools
    print("\nTest: '今天睡得怎么样？' with 21 tools")
    print("-" * 60)

    response, tool_calls = llm.generate_response(
        message="今天睡得怎么样？",
        context=[],
        tools=TOOLS_SCHEMA,
        images=None
    )

    print(f"Response length: {len(response) if response else 0}")
    print(f"Tool calls: {tool_calls}")

    if response or tool_calls:
        print("\n✅ SUCCESS - Direct Google API works!")
        print(f"Response preview: {response[:300] if response else 'N/A'}")
        if tool_calls:
            print(f"Tool calls: {[tc['name'] for tc in tool_calls]}")
    else:
        print("\n❌ FAILED - Even direct API doesn't work")
        print("This might be an API key issue or region restriction")

except Exception as e:
    print(f"\n❌ Error: {e}")
    print("\nPossible issues:")
    print("1. Invalid Google API key")
    print("2. API not enabled in Google Cloud Console")
    print("3. Region restrictions")
    print("4. Billing not set up")
