from unittest.mock import MagicMock, patch

from GramAddict.core.bot_flow import _run_zero_latency_feed_loop


def test_run_zero_latency_feed_loop_name_error_regression():
    """
    TDD RED PHASE: This test should FAIL with NameError: name '_detect_ad_structural' is not defined.
    """
    mock_device = MagicMock()
    mock_device.dump_hierarchy.return_value = "<?xml version='1.0' ?><hierarchy><node text='test'/></hierarchy>"

    # Mock DopamineEngine
    mock_dopamine = MagicMock()
    mock_dopamine.is_app_session_over.side_effect = [False, True]  # Run once then exit
    mock_dopamine.wants_to_change_feed.return_value = False
    mock_dopamine.wants_to_doomscroll.return_value = False

    mock_stack = {"dopamine": mock_dopamine, "radome": MagicMock(), "ai": MagicMock(), "growth": MagicMock()}

    mock_session_state = MagicMock()
    mock_session_state.check_limit.return_value = (False,)  # any() will be False

    # We want it to reach line 896 where _detect_ad_structural is called
    mock_zero_engine = MagicMock()
    mock_nav_graph = MagicMock()
    mock_configs = MagicMock()

    # Mocking globals
    with (
        patch("GramAddict.core.bot_flow._humanized_scroll"),
        patch("GramAddict.core.bot_flow.logger"),
        patch("GramAddict.core.bot_flow.random_sleep"),
        patch("GramAddict.core.bot_flow.ResonanceEngine"),
        patch("GramAddict.core.bot_flow.ZeroLatencyEngine"),
    ):
        # Should now run without NameError
        _run_zero_latency_feed_loop(
            mock_device, mock_zero_engine, mock_nav_graph, mock_configs, mock_session_state, "ExploreFeed", mock_stack
        )
