from unittest.mock import MagicMock, patch

import pytest

from GramAddict.core.behaviors import BehaviorContext
from GramAddict.core.behaviors.rabbit_hole import RabbitHolePlugin


@pytest.fixture
def rabbit_hole():
    return RabbitHolePlugin()


@pytest.fixture
def mock_context():
    ctx = BehaviorContext(
        device=MagicMock(),
        configs=MagicMock(),
        session_state=MagicMock(),
        cognitive_stack={"nav_graph": MagicMock()},
        context_xml="<xml></xml>",
        shared_state={"res_score": 0.95},
    )
    return ctx


class TestRabbitHolePlugin:
    @patch("GramAddict.core.behaviors.rabbit_hole.sleep")
    def test_execute_success(self, mock_sleep, rabbit_hole, mock_context):
        mock_context.cognitive_stack["nav_graph"].do.return_value = True

        result = rabbit_hole.execute(mock_context)

        assert result.executed is True
        mock_context.cognitive_stack["nav_graph"].do.assert_called_once_with("tap post username")
        mock_context.device.press.assert_called_once_with("back")
        assert mock_sleep.call_count == 2

    def test_can_activate_low_resonance(self, rabbit_hole, mock_context):
        mock_context.shared_state["res_score"] = 0.5

        assert rabbit_hole.can_activate(mock_context) is False

    def test_can_activate_success(self, rabbit_hole, mock_context):
        mock_context.configs.get_plugin_config.return_value = {"percentage": 100}
        with patch("GramAddict.core.behaviors.rabbit_hole.random.random", return_value=0.0):
            assert rabbit_hole.can_activate(mock_context) is True

    def test_execute_no_nav_graph(self, rabbit_hole, mock_context):
        mock_context.cognitive_stack.pop("nav_graph")

        result = rabbit_hole.execute(mock_context)

        assert result.executed is False  # Fails to execute if no nav_graph
