from unittest.mock import MagicMock, patch

from GramAddict.core.bot_flow import _interact_with_profile
from GramAddict.core.session_state import SessionState


class FakeConfig:
    def __init__(self):
        self.args = MagicMock()
        self.args.follow_percentage = 100
        self.args.likes_percentage = 100
        self.args.stories_percentage = 0
        self.args.likes_count = "1-1"

    def get_plugin_config(self, name):
        return {}


def test_profile_grid_sync_delay_after_follow():
    """
    Verifies that _interact_with_profile enforces a sleep delay
    after a successful follow and BEFORE searching for the grid,
    preventing UI automation from dumping mid-animation.
    It now tracks the autonomous QNavGraph calls.
    """
    mock_device = MagicMock()
    mock_device.app_id = "com.instagram.android"
    mock_device.dump_hierarchy.return_value = "<hierarchy><node package='com.instagram.android' resource-id='com.instagram.android:id/profile_header' /><node text='following' /><node text='followers' /></hierarchy>"
    mock_configs = FakeConfig()

    mock_session_state = MagicMock(spec=SessionState)
    mock_session_state.check_limit.return_value = False

    manager = MagicMock()

    with (
        patch("GramAddict.core.q_nav_graph.QNavGraph") as MockQNavGraph,
        patch("GramAddict.core.bot_flow.sleep"),
        patch("GramAddict.core.behaviors.follow.sleep") as mock_sleep,
        patch("GramAddict.core.behaviors.grid_like.wait_for_post_loaded", return_value=True),
        patch("random.random", return_value=0.0),
    ):  # Use global random patch for local import robustness
        mock_nav_instance = MagicMock()
        mock_nav_instance.do.return_value = True  # Always succeed transition
        MockQNavGraph.return_value = mock_nav_instance

        manager.attach_mock(mock_nav_instance.do, "do")
        manager.attach_mock(mock_sleep, "sleep")

        mock_stack = {"growth_brain": MagicMock()}

        from GramAddict.core.behaviors import PluginRegistry
        from GramAddict.core.behaviors.follow import FollowPlugin
        from GramAddict.core.behaviors.grid_like import GridLikePlugin

        registry = PluginRegistry.get_instance()
        registry.register(FollowPlugin())
        registry.register(GridLikePlugin())

        # Act
        _interact_with_profile(mock_device, mock_configs, "test_user", mock_session_state, 1.0, MagicMock(), mock_stack)

        follow_idx = -1
        grid_idx = -1

        for i, mock_call in enumerate(manager.mock_calls):
            # mock_call format: ('name', (args,), {kwargs})
            if mock_call[0] == "do":
                args = mock_call[1]
                if args and args[0] == "tap follow button":
                    follow_idx = i
                elif args and args[0] == "tap first image post in profile grid":
                    grid_idx = i

        assert follow_idx != -1, "Follow transition was not executed"
        assert grid_idx != -1, "Grid interaction was not executed"
        assert follow_idx < grid_idx, "Follow must happen before grid interaction"

        # Verify that more than 1.5s delay happened between follow and grid interaction
        # (The bot_flow.py uses random.uniform(1.8, 3.2))
        found_delay = False
        for i in range(follow_idx + 1, grid_idx):
            if manager.mock_calls[i][0] == "sleep":
                sleep_val = manager.mock_calls[i][1][0]
                if sleep_val >= 1.5:
                    found_delay = True
                    break

        assert found_delay, "No significant sleep delay found between follow and grid interaction"
