import pytest
import os
from slack_bot.llm.gemini import GeminiLLM
from slack_bot.tools.registry import TOOLS_SCHEMA

@pytest.fixture
def live_gemini():
    """Validates env usage and returns a live Gemini wrapper."""
    if not os.environ.get("GEMINI_API_KEY"):
        pytest.skip("GEMINI_API_KEY not found in environment, skipping live test.")
    
    # Force real implementation, logic in conftest might mock it
    # But since we import GeminiLLM directly here, it should be fine unless sys.modules is patched
    return GeminiLLM()

@pytest.mark.live_llm
class TestLiveGym:
    """Live tests aginst the real Gemini API. Costs money!"""

    def test_hello_world(self, live_gemini):
        """Simple smoke test."""
        resp, _ = live_gemini.generate_response("Say hello", [], tools=None)
        assert len(resp) > 0
        assert "Gemini Error" not in resp

    def test_tool_selection_diet(self, live_gemini):
        """Verify the model can select the correct tool for diet logging."""
        prompt = "I ate a banana for breakfast"
        resp, tools = live_gemini.generate_response(prompt, [], tools=TOOLS_SCHEMA)
        
        # It might just reply text "I logged it", but we want to check tool calls
        # Usually it should produce a tool call
        assert tools is not None
        assert len(tools) > 0
        
        # Check first tool call
        tool_call = tools[0]
        assert tool_call["name"] == "log_diet"
        assert "banana" in tool_call["args"]["description"].lower()
        # It might infer date as today
        assert "target_date" in tool_call["args"]

    def test_tool_selection_read_stats(self, live_gemini):
        """Verify reading stats tool selection."""
        prompt = "How was my sleep yesterday?"
        resp, tools = live_gemini.generate_response(prompt, [], tools=TOOLS_SCHEMA)
        
        assert tools is not None
        assert len(tools) > 0
        topic_tools = ["get_daily_detailed_stats", "get_metric_history"]
        assert tools[0]["name"] in topic_tools
