import os
from unittest.mock import MagicMock, patch

# Mock directory setup
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FIXTURE_DIR = os.path.join(ROOT_DIR, "fixtures")


class ConfigMock:
    def __init__(self):
        self.args = MagicMock()
        self.args.app_id = "com.instagram.android"


def test_fsd_handles_persistent_survey_modal():
    """
    Simulates a case where the bot gets stuck on a survey modal.
    The FSD (Full Self Driving) anomaly handler should trigger,
    detect that 'Back' didn't work, and engage TelepathicEngine
    to find and tap the 'Not Now' or 'Dismiss' button.
    """
    from GramAddict.core.bot_flow import _run_zero_latency_feed_loop

    device = MagicMock()
    device.app_id = "com.instagram.android"
    device._get_current_app.return_value = "com.instagram.android"
    configs = ConfigMock()

    # Mock the TelepathicEngine singleton behavior entirely
    mock_telepathic = MagicMock()
    mock_telepathic.find_best_node.return_value = {"x": 500, "y": 1400, "semantic": "Not Now"}

    dopamine = MagicMock()
    dopamine.is_app_session_over.side_effect = [False, False, True]  # Run twice, then exit
    dopamine.wants_to_change_feed.return_value = False
    dopamine.wants_to_doomscroll.return_value = False

    ai = MagicMock()
    ai.get_sleep_modifier.return_value = 1.0

    cognitive_stack = {
        "dopamine": dopamine,
        "growth_brain": None,
        "active_inference": ai,
    }

    # Load the mock survey modal UI
    xml_path = os.path.join(FIXTURE_DIR, "survey_modal.xml")
    with open(xml_path, "r") as f:
        alien_xml = f.read()
    device.dump_hierarchy.return_value = alien_xml

    with (
        patch("GramAddict.core.bot_flow.sleep"),
        patch("GramAddict.core.behaviors.obstacle_guard.sleep"),
        patch("GramAddict.core.bot_flow._humanized_scroll"),
        patch("GramAddict.core.behaviors.obstacle_guard.TelepathicEngine.get_instance", return_value=mock_telepathic),
        patch("GramAddict.core.telepathic_engine.TelepathicEngine.get_instance", return_value=mock_telepathic),
    ):
        from GramAddict.core.behaviors import PluginRegistry
        from GramAddict.core.behaviors.obstacle_guard import ObstacleGuardPlugin

        PluginRegistry.get_instance().register(ObstacleGuardPlugin())

        _run_zero_latency_feed_loop(device, None, MagicMock(), configs, MagicMock(), "HomeFeed", cognitive_stack)

        # VERIFICATION:
        assert mock_telepathic.find_best_node.called
        assert device.click.called
