#!/usr/bin/env python3
"""
Test the EXACT scenario that fails: health query with full system prompt and tools.
"""

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

from health.utils.env_loader import load_env_with_extras
from openai import OpenAI
from slack_bot.llm.gemini import get_system_instruction
from slack_bot.tools.registry import TOOLS_SCHEMA

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")

# Get full system prompt
system_prompt = get_system_instruction()

print("=" * 60)
print("Testing the EXACT failing scenario")
print("=" * 60)
print(f"System prompt length: {len(system_prompt)}")
print(f"Tools count: {len(TOOLS_SCHEMA)}")
print()

# Test 1: Full setup WITH tool_choice
print("Test 1: WITH tool_choice='auto'")
print("-" * 60)

try:
    response1 = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": "今天睡得怎么样？"}
        ],
        tools=TOOLS_SCHEMA,
        tool_choice="auto"
    )
    content1 = response1.choices[0].message.content or ""
    finish1 = response1.choices[0].finish_reason
    has_tools1 = hasattr(response1.choices[0].message, 'tool_calls') and response1.choices[0].message.tool_calls

    print(f"✅ Request succeeded")
    print(f"   Finish reason: {finish1}")
    print(f"   Response length: {len(content1)}")
    print(f"   Has tool_calls: {has_tools1}")
    print(f"   Status: {'✅ WORKS' if content1 or has_tools1 else '❌ EMPTY'}")
except Exception as e:
    print(f"❌ Request failed: {e}")

print()

# Test 2: Full setup WITHOUT tool_choice
print("Test 2: WITHOUT tool_choice")
print("-" * 60)

try:
    response2 = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": "今天睡得怎么样？"}
        ],
        tools=TOOLS_SCHEMA
        # NO tool_choice parameter
    )
    content2 = response2.choices[0].message.content or ""
    finish2 = response2.choices[0].finish_reason
    has_tools2 = hasattr(response2.choices[0].message, 'tool_calls') and response2.choices[0].message.tool_calls

    print(f"✅ Request succeeded")
    print(f"   Finish reason: {finish2}")
    print(f"   Response length: {len(content2)}")
    print(f"   Has tool_calls: {has_tools2}")
    print(f"   Status: {'✅ WORKS' if content2 or has_tools2 else '❌ EMPTY'}")
except Exception as e:
    print(f"❌ Request failed: {e}")

print()
print("=" * 60)
print("CONCLUSION:")
print("=" * 60)
print("If Test 2 (without tool_choice) works but Test 1 fails,")
print("then the solution is to remove 'tool_choice' parameter!")
