#!/usr/bin/env python3
"""
Binary search to find problematic part of system prompt.
"""

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

load_env_with_extras()

client = OpenAI(
    api_key=os.environ.get("GEMINI_API_KEY"),
    base_url=f"{os.environ.get('GEMINI_BASE_URL')}/v1"
)
model = os.environ.get("GEMINI_MODEL", "gemini-3-flash")

full_prompt = get_system_instruction()

print("=" * 60)
print("Binary Search for Problematic Content")
print("=" * 60)
print(f"Full prompt length: {len(full_prompt)}")

# Test full prompt
print("\nTest: Full system prompt")
print("-" * 60)
try:
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": full_prompt},
            {"role": "user", "content": "今天睡得怎么样？"}
        ]
    )
    content = response.choices[0].message.content or ""
    print(f"{'✅ WORKS' if content else '❌ EMPTY'} - {len(content)} chars")
except Exception as e:
    print(f"❌ Error: {str(e)[:100]}")

# Test first half
half_point = len(full_prompt) // 2
first_half = full_prompt[:half_point]

print(f"\nTest: First half ({len(first_half)} chars)")
print("-" * 60)
try:
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": first_half},
            {"role": "user", "content": "今天睡得怎么样？"}
        ]
    )
    content = response.choices[0].message.content or ""
    print(f"{'✅ WORKS' if content else '❌ EMPTY'} - {len(content)} chars")
except Exception as e:
    print(f"❌ Error: {str(e)[:100]}")

# Test second half
second_half = full_prompt[half_point:]

print(f"\nTest: Second half ({len(second_half)} chars)")
print("-" * 60)
try:
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": second_half},
            {"role": "user", "content": "今天睡得怎么样？"}
        ]
    )
    content = response.choices[0].message.content or ""
    print(f"{'✅ WORKS' if content else '❌ EMPTY'} - {len(content)} chars")
except Exception as e:
    print(f"❌ Error: {str(e)[:100]}")

print("\n" + "=" * 60)
print("If full fails but both halves work:")
print("  → Problem is in the COMBINATION/LENGTH")
print("If one half fails:")
print("  → Problem is in THAT specific content")
