import logging

import pytest

from GramAddict.core.navigation.brain import ask_brain_for_action

logger = logging.getLogger(__name__)

# ── Stochastic LLM Tests ──
# LLMs are non-deterministic. A single run proves nothing.
# We run N times and assert that at least X/N responses are valid.
# This catches SYSTEMATIC failures (empty responses, thinking leaks)
# while tolerating genuine LLM variance.

STOCHASTIC_RUNS = 5
MIN_VALID_RATIO = 0.6  # At least 60% must return valid actions


@pytest.mark.live_llm
def test_brain_recommends_valid_action_when_trapped():
    """
    Test that the real, live LLM Brain returns valid actions at a statistically
    significant rate. Accounts for reasoning models that sometimes return
    response='' (which our pipeline correctly treats as None).
    """
    goal = "open following list"
    screen = "OWN_PROFILE"
    available_actions = [
        "tap share button",
        "press back",
        "tap reels tab",
        "tap messages tab",
        "scroll down",
        "scroll up",
    ]
    explored_nav_actions = {"tap following list"}

    valid_results = []
    none_results = []

    for i in range(STOCHASTIC_RUNS):
        brain_action = ask_brain_for_action(
            goal=goal,
            screen_type=screen,
            available_actions=available_actions,
            explored_actions=explored_nav_actions,
        )

        if brain_action is not None and brain_action in available_actions:
            valid_results.append(brain_action)
        else:
            none_results.append(brain_action)

        logger.info(f"[Run {i+1}/{STOCHASTIC_RUNS}] Brain returned: '{brain_action}'")

    min_required = int(STOCHASTIC_RUNS * MIN_VALID_RATIO)
    assert len(valid_results) >= min_required, (
        f"Brain returned valid actions in only {len(valid_results)}/{STOCHASTIC_RUNS} runs "
        f"(minimum required: {min_required}). "
        f"None results: {none_results}. Valid results: {valid_results}"
    )

    # Bonus: verify no result was from an action we already explored
    for action in valid_results:
        assert action not in explored_nav_actions, (
            f"Brain returned explored/failed action '{action}' — masking is broken!"
        )
