"""
E2E: Permission Dialog Workflow
================================
Tests the FULL production pipeline when the device shows an Android
permission dialog (e.g., "Allow Instagram to record audio?").

Mock: ONLY the device (XML dumps).
Real: Cognitive stack, PluginRegistry, SessionState, Config.
"""

PERMISSION_DIALOG_XML = """<?xml version="1.0" encoding="utf-8"?>
<hierarchy rotation="0">
    <node class="android.widget.FrameLayout" package="com.android.permissioncontroller"
          bounds="[0,0][1080,2400]">
        <node resource-id="com.android.permissioncontroller:id/grant_dialog"
              class="android.widget.LinearLayout" package="com.android.permissioncontroller"
              clickable="false" bounds="[100,800][980,1600]">
            <node text="Allow Instagram to record audio?"
                  class="android.widget.TextView"
                  resource-id="com.android.permissioncontroller:id/permission_message" />
            <node text="While using the app"
                  class="android.widget.Button" clickable="true"
                  resource-id="com.android.permissioncontroller:id/permission_allow_foreground_only_button"
                  bounds="[100,1000][980,1100]" />
            <node text="Don't allow"
                  class="android.widget.Button" clickable="true"
                  resource-id="com.android.permissioncontroller:id/permission_deny_button"
                  bounds="[100,1240][980,1340]" />
        </node>
    </node>
</hierarchy>
"""

NORMAL_POST_XML = """<?xml version="1.0" encoding="utf-8"?>
<hierarchy rotation="0">
    <node class="android.widget.FrameLayout" package="com.instagram.android"
          bounds="[0,0][1080,2400]">
        <node resource-id="com.instagram.android:id/row_feed_photo_profile_name"
              class="android.widget.TextView" text="photographer_jane"
              clickable="true" bounds="[160,300][600,340]" />
        <node resource-id="com.instagram.android:id/row_feed_button_like"
              class="android.widget.ImageView" clickable="true"
              content-desc="Like" bounds="[30,1360][120,1450]" />
    </node>
</hierarchy>
"""


def test_permission_dialog_terminates_chain(make_real_device_with_xml, e2e_workflow_ctx):
    """
    PRODUCTION BUG 2026-04-29: Bot got stuck on "Allow Instagram to record audio?"
    because obstacle_guard ignored OBSTACLE_SYSTEM and downstream plugins fired
    against a PermissionController XML tree.

    The full pipeline must: detect → press BACK → skip all interactions.
    """

    device = make_real_device_with_xml([PERMISSION_DIALOG_XML, NORMAL_POST_XML])
    results, ctx = e2e_workflow_ctx(device, context_xml=PERMISSION_DIALOG_XML)

    # Chain must have set should_skip=True
    guard_fired = any(r.executed and r.should_skip for r in results)
    assert guard_fired, (
        "obstacle_guard did not fire — the bot would continue interacting " "with a permission dialog in production!"
    )

    # Zero interactions on a permission dialog
    total_interactions = sum(r.interactions for r in results)
    assert total_interactions == 0, f"{total_interactions} interaction(s) performed on a permission dialog!"

    # BACK must have been pressed
    assert "back" in device.pressed_keys, "obstacle_guard did not press BACK — the dialog stays on screen!"


def test_sae_escapes_permission_dialog_via_vlm(make_real_device_with_xml):
    """
    Ensures that the SituationalAwarenessEngine's ensure_clear_screen loop
    can correctly use the VLM to escape an OBSTACLE_SYSTEM dialog.
    """
    from GramAddict.core.situational_awareness import SituationalAwarenessEngine

    # First XML is the permission dialog, second is the normal feed.
    device = make_real_device_with_xml([PERMISSION_DIALOG_XML, NORMAL_POST_XML])
    sae = SituationalAwarenessEngine.get_instance(device)

    # We must wipe Qdrant memory for this situation so it forces an LLM call.
    _ = sae._compress_xml(PERMISSION_DIALOG_XML)
    sae.episodes.recall = lambda x: None  # Force LLM instead of recalled memory for test determinism

    # Ensure clear screen MUST return True, meaning it successfully cleared the obstacle.
    success = sae.ensure_clear_screen(max_attempts=3, initial_xml=PERMISSION_DIALOG_XML)

    assert success is True, "ensure_clear_screen failed to escape the system dialog!"

    # Verify that the LLM decided to either click the 'Don't allow' button or press BACK.
    # The 'Don't allow' button is at [100,1240][980,1340], center is (540, 1290).
    clicked_deny = any(abs(x - 540) < 50 and abs(y - 1290) < 50 for x, y in device.clicks)
    pressed_back = "back" in device.pressed_keys

    assert clicked_deny or pressed_back, "VLM failed to click the 'Don't allow' button or press back!"
