import GramAddict.core.navigation.brain
from GramAddict.core.navigation.planner import GoalPlanner
from GramAddict.core.perception.screen_identity import ScreenType


def test_planner_falls_back_to_brain_when_hd_map_fails(monkeypatch):
    """
    Test that if HD Map routing fails because the structural target is not visible
    (and thus in explored_nav_actions), the planner falls back to the Brain
    to dynamically pick an action like 'scroll down'.
    """
    planner = GoalPlanner("testuser")

    # Simulate a screen where the target isn't visible
    screen = {
        "screen_type": ScreenType.OWN_PROFILE,
        "available_actions": ["press back", "scroll down", "tap profile tab"],
        "context": {},
    }

    # Simulate that 'tap following list' failed previously and is in explored actions
    explored = {"tap following list"}

    # The brain should realize that 'scroll down' is the best way to uncover the target
    query_args = []

    def mock_query_llm(**kwargs):
        query_args.append(kwargs)
        return {"response": "scroll down"}

    monkeypatch.setattr(GramAddict.core.navigation.brain, "query_llm", mock_query_llm)

    action = planner.plan_next_step("go to followers/following list", screen, explored_nav_actions=explored)

    # Verify the brain was queried
    assert len(query_args) == 1
    assert "go to followers/following list" in query_args[0]["system"]

    # Verify the brain's parsed decision is respected by the planner
    assert action == "scroll down"
