#!/usr/bin/env python3
"""
Test different tool_choice settings to find what works with your proxy.
"""

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

from health.utils.env_loader import load_env_with_extras
from openai import OpenAI

load_env_with_extras()

api_key = os.environ.get("GEMINI_API_KEY")
base_url = os.environ.get("GEMINI_BASE_URL")
model = os.environ.get("GEMINI_MODEL", "gemini-3-flash")

client = OpenAI(api_key=api_key, base_url=f"{base_url}/v1")

# Simple tool definition
simple_tool = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string"}
            },
            "required": ["city"]
        }
    }
}

test_cases = [
    ("No tools", None, None),
    ("With tools, no tool_choice", [simple_tool], None),
    ("With tools, tool_choice='auto'", [simple_tool], "auto"),
    ("With tools, tool_choice='none'", [simple_tool], "none"),
]

print("=" * 60)
print("Testing tool_choice parameter compatibility")
print("=" * 60)

for test_name, tools, tool_choice in test_cases:
    print(f"\n{test_name}")
    print("-" * 60)

    kwargs = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Hello"}
        ]
    }

    if tools:
        kwargs["tools"] = tools
    if tool_choice:
        kwargs["tool_choice"] = tool_choice

    try:
        response = client.chat.completions.create(**kwargs)
        content = response.choices[0].message.content or ""
        finish_reason = response.choices[0].finish_reason

        print(f"✅ SUCCESS")
        print(f"   Finish reason: {finish_reason}")
        print(f"   Response length: {len(content)}")
        print(f"   Has content: {bool(content)}")

    except Exception as e:
        print(f"❌ FAILED: {str(e)[:200]}")

print("\n" + "=" * 60)
print("HYPOTHESIS:")
print("=" * 60)
print("If 'tool_choice=auto' fails but 'no tool_choice' works,")
print("then your proxy doesn't support the tool_choice parameter.")
print("\nOpenRouter properly handles tool_choice, but your proxy might:")
print("1. Not recognize this parameter")
print("2. Have a bug in handling it")
print("3. Require a different format")
