from GramAddict.core.behaviors import BehaviorContext
from GramAddict.core.behaviors.obstacle_guard import ObstacleGuardPlugin
from GramAddict.core.situational_awareness import SituationalAwarenessEngine, SituationType


class DummyDeviceV2:
    def __init__(self):
        self.info = {"screenOn": True}


class DummyDevice:
    def __init__(self):
        self.deviceV2 = DummyDeviceV2()
        self.app_id = "com.instagram.android"
        self.pressed = []

    def press(self, key):
        self.pressed.append(key)


def test_sae_detects_obstacle_keyboard():
    """
    TDD: Prove that the SAE detects the on-screen keyboard as an obstacle.
    """
    real_device = DummyDevice()
    sae = SituationalAwarenessEngine.get_instance(real_device)

    xml_with_keyboard = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
    <hierarchy rotation="0">
      <node index="0" package="com.instagram.android" resource-id="" text="" content-desc="" />
      <node index="1" class="android.widget.EditText" focused="true" />
      <node index="2" package="com.google.android.inputmethod.latin" resource-id="com.google.android.inputmethod.latin:id/keyboard_view" text="" content-desc="Keyboard" />
    </hierarchy>
    """

    situation = sae.perceive(xml_with_keyboard)
    assert situation == SituationType.OBSTACLE_KEYBOARD


def test_obstacle_guard_dismisses_keyboard():
    """
    TDD: Prove that ObstacleGuardPlugin handles OBSTACLE_KEYBOARD by pressing BACK.
    """
    real_device = DummyDevice()

    xml_with_keyboard = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
    <hierarchy rotation="0">
      <node index="0" package="com.instagram.android" resource-id="" text="" content-desc="" />
      <node index="1" class="android.widget.EditText" focused="true" />
      <node index="2" package="com.google.android.inputmethod.latin" resource-id="com.google.android.inputmethod.latin:id/keyboard_view" text="" content-desc="Keyboard" />
    </hierarchy>
    """

    class DummySessionState:
        job_target = "test"

    ctx = BehaviorContext(
        device=real_device,
        session_state=DummySessionState(),
        shared_state={},
        context_xml=xml_with_keyboard,
        configs=None,
        cognitive_stack=None,
    )

    plugin = ObstacleGuardPlugin()
    result = plugin.execute(ctx)

    # Assert it recognized and handled the keyboard
    assert "back" in real_device.pressed
    assert result.executed is True
    assert result.should_skip is True
