from unittest.mock import MagicMock, patch

import pytest

from GramAddict.core.behaviors.profile_visit import ProfileVisitPlugin


@pytest.fixture
def profile_visit_plugin():
    return ProfileVisitPlugin()


@pytest.fixture
def mock_context():
    ctx = MagicMock()
    ctx.configs = MagicMock()
    ctx.configs.args.profile_visit_percentage = 30
    ctx.configs.get_plugin_config.return_value = {"percentage": 30}
    ctx.shared_state = {"res_score": 1.0}
    ctx.context_xml = "<xml></xml>"
    ctx.device = MagicMock()
    ctx.username = "test_user"

    mock_nav = MagicMock()
    mock_nav.current_state = "HomeFeed"
    ctx.cognitive_stack = {"nav_graph": mock_nav}
    return ctx


class TestProfileVisitPlugin:
    @patch("GramAddict.core.behaviors.profile_visit.random.random", return_value=0.1)  # 0.1 < 0.3
    def test_can_activate_enabled(self, mock_random, profile_visit_plugin, mock_context):
        assert profile_visit_plugin.can_activate(mock_context) is True

    def test_can_activate_disabled_via_config(self, profile_visit_plugin, mock_context):
        mock_context.configs.get_plugin_config.return_value = {"percentage": 0}
        assert profile_visit_plugin.can_activate(mock_context) is False

    @patch("GramAddict.core.behaviors.profile_visit.sleep")
    @patch("GramAddict.core.behaviors.PluginRegistry")
    def test_execute_success(self, mock_registry, mock_sleep, profile_visit_plugin, mock_context):
        mock_nav = mock_context.cognitive_stack["nav_graph"]
        mock_nav.do.return_value = True

        mock_registry_instance = MagicMock()
        mock_registry.get_instance.return_value = mock_registry_instance

        from GramAddict.core.behaviors import BehaviorResult

        mock_registry_instance.execute_all.return_value = [BehaviorResult(executed=True)]

        result = profile_visit_plugin.execute(mock_context)

        assert result.executed is True
        mock_nav.do.assert_any_call("tap post username")
        mock_context.device.press.assert_called_with("back")
